问题
Does .NET natively support anything similar to PHP's variable variables?
If not, how1 could such a feature be most easily implemented?
1 If you think variable variables are always bad, feel free to state your case but the main question is: how can they be implemented?
回答1:
This is a feature deeply embedded in dynamic languages. C# has its roots as a static, object-oriented language, and up to C# 3.0 this means no luck accomplishing what you want in any proper way. However, C# 4.0/.NET 4.0 introduces the dynamic keyword, which allows variables to be dynamically typed, as in PHP. Unfortunately, although this is a leap forward in the path of C# becoming a static/dynamic hybrid language, it is missing the crucial eval
function that almost every dynamic language has. With the rumoured compiler-as-a-service feature of C# 5.0/.NET 5.0, this will effectively be introduced (though the internal behaviour would not be the same). Until then, there's no decent solution short of the hack of using a Dictionary
to store variable names.
回答2:
Why not just use a Dictionary ?
Dictionary<string,string> stuffHash = new Dictionary<string,string>();
string varname = "TheNameOfTheVar";
string value = "foo";
stuffHash[varname] = value;
No actual need to do this ugly thing.
回答3:
.Net does not support "variable variables" natively - probably mainly because it is a [strongly typed language][1].
However, it does have support for dynamically creating instances of a type, at runtime, which could be used to accomplish similar behaviors as the PHP variable variables.
回答4:
No, none of the .NET languages support anything like this. This could be implemented by one of the compiler teams but I doubt they would ever do it.
As to how this could be implemented by you (not by the C# compiler team) would be to store all of your variable variables in a Dictionary<String,Object>
- this would allow you to associate a string with an object.
I have never really understood what problem is solved by variable variables (in other words, I have never heard a good argument for needing to use them). I would be interested to see an example where they were needed as I would imagine it wouldn't be too hard to find a better approach to solving the problem without variable variables.
来源:https://stackoverflow.com/questions/1347657/php-variable-variables-in-net