I want to set a variable in a class. But I want to dynamically choose which variable to set.
In PHP :
<?PHP
class Foo {
var $Bar="Blah";
}
$ClassVar = new Foo();
$Variable = "Bar";
$ClassVar->$Variable = "Poo";
echo "Output : ".$ClassVar->Bar开发者_如何学运维;
?>
Output : Poo
I want to do the same in VB.NET
In VB you’d use a dictionary to achieve this.
Dim x As New Dictionary(Of String, String)()
x.Add("Bar", "Blah")
Dim variable = "Bar"
x(variable) = "Poo"
Console.WriteLine(x("Bar"))
Although this is more reminiscent of the PHP array
. It is actually possible to get the same effect in VB as in your PHP code, using reflection. But VB is a different language and in VB you’d normally not write such a code. Even more strongly: when you find yourself writing such code in VB, it’s almost always a sign of a serious flaw in your code design.
But just for completeness’ sake:
Dim obj As New Foo()
CallByName(obj, "Bar", CallType.Let, "Poo")
However, this only works when Bar
is in fact a property, not a variable (it also works with a variable but that’s more difficult still).
精彩评论