Sea*_*ean 4 c# variables if-statement function
有什么方法可以调用带变量的函数吗?
variable+"()";
Run Code Online (Sandbox Code Playgroud)
或类似的东西,或者我必须使用if语句?
转换似乎可能是答案,所以如果变量的值= var1,我希望它执行var1(); 如果值为var2,我希望它执行var2(); 我该怎么编码呢?
基本上,我试图找到一个更清洁的替代品
if (variable == var1)
{
var1();
}
if (variable == var2)
{
var2();
}
Run Code Online (Sandbox Code Playgroud)
可以使用反射来查找对象中的方法并调用该方法,但最简单和最快的方法是简单地使用一个开关:
switch (variable) {
case "OneMethod": OneMethod(); break;
case "OtherMethod": OtherMethod(); break;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Reflection http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx按名称访问任何函数或成员.虽然需要一些时间来适应.它也有性能问题,所以如果你可以避免使用它,你应该.