不适用于 C# 或任何静态类型语言。
出于好奇,我尝试了我在 PHP 中记住的内容(动态创建变量)是否仍然正确。
它仍然是相同的 PHP,我上次使用它是在 2000 年。您可以即时生成变量,但并不是说它是可取的,它会污染全局变量,它可能会破坏一些现有的变量或同名对象。
https://ideone.com/nJDiou
<?php
class MyClass
{
private $v;
function __construct($x) {
$this->v = $x;
}
public function getValue() {
return $this->v;
}
}
$one = new MyClass("I'm tough!");
echo "The one: " . $one->getValue() . "\n";
$i = 0;
foreach(array("one","two","three") as $h) {
$$h = new MyClass("Says who? " . ++$i);
}
echo "The one: " . $one->getValue() . "\n";
echo $two->getValue() . "\n";
echo $three->getValue() . "\n";
echo "loop\n";
foreach(array("three","one","two") as $h) {
echo $$h->getValue() . "\n";
}
?>
输出:
The one: I'm tough!
The one: Says who? 1
Says who? 2
Says who? 3
loop
Says who? 3
Says who? 1
Says who? 2