生病使用交换机/ case语句。我想知道是否有某种方法可以根据用户提供的值调用方法。要知道,有可能是一万个理由,为什么这是一个坏主意,但在这里就是我想:
Console.Write("What method do you want to call? ");
string method_name = Console.ReadLine();
然后以某种方式调用包含在“METHOD_NAME”的方法。这甚至有可能吗?
生病使用交换机/ case语句。我想知道是否有某种方法可以根据用户提供的值调用方法。要知道,有可能是一万个理由,为什么这是一个坏主意,但在这里就是我想:
Console.Write("What method do you want to call? ");
string method_name = Console.ReadLine();
然后以某种方式调用包含在“METHOD_NAME”的方法。这甚至有可能吗?
如果你想,你可以以某种方式做到这一点:
Console.Write("What method do you want to call? ");
string method_name = Console.ReadLine();
method_name();
你就错了。您必须分析用户输入并根据该输入调用方法。如果你想要的类型是动态的,以及该方法然后用这个来代替typeof(MyClass)
var type = typeof(MyClass);
var method = type.GetMethod(method_name);
method.Invoke(obj, params);
:
您可以使用反射
var type = Type.GetType(type_name);
当然,reflection是你的朋友。看看Type.GetMethod()
。
你的样品
public class Boss
{
public void Kick()
{
Console.WriteLine("Kick");
}
public void Talk(string message)
{
Console.WriteLine("Talk " + message);
}
public void Run()
{
Console.WriteLine("Run");
}
}
class Program
{
static void AutoSwitch(object obj, string methodName, params object[] parameters)
{
var objType = typeof(obj);
var method = objType.GetMethod(methodName);
method.Invoke(obj, parameters);
}
static void Main(string[] args)
{
var obj = new Boss();
AutoSwitch(obj, "Talk", "Hello World");
AutoSwitch(obj, "Kick");
}
}
而是反思的,如果你有作用于用户的输入值W/O使用switch语句,你可以使用具有映射对输入值的方法列表的字典。
private static void Method1(int x)
{
Console.WriteLine(x);
}
private static void Method2(int x)
{
}
private static void Method3(int x)
{
}
static void Main(string[] args)
{
Dictionary<int, Action<int>> methods = new Dictionary<int, Action<int>>();
methods.Add(1, Method1);
methods.Add(2, Method2);
methods.Add(3, Method3);
(methods[1])(1);
}
我所看到的处理(读忌)switch语句的另一种有趣的方式不同的是使用的方法的字典。我偷了这个来自http://www.markhneedham.com/blog/2010/05/30/c-using-a-dictionary-instead-of-if-statements/,它看起来像他们正在使用的MVC框架,但同样的基本原则适用
public class SomeController
{
private Dictionary<string, Func<UserData,ActionResult>> handleAction =
new Dictionary<string, Func<UserData,ActionResult>>
{ { "Back", SaveAction },
{ "Next", NextAction },
{ "Save", SaveAction } };
public ActionResult TheAction(string whichButton, UserData userData)
{
if(handleAction.ContainsKey(whichButton))
{
return handleAction[whichButton](userData);
}
throw Exception("");
}
private ActionResult NextAction(UserData userData)
{
// do cool stuff
}
}
很多时候,你可以重构switch语句到字典...
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
case 3:
Console.WriteLine("Case 3");
break;
}
能成。 ...
var replaceSwitch = new Dictionary<int, Action>
{
{ 1,() => Console.WriteLine("Case 1") }
{ 2,() => Console.WriteLine("Case 2") }
{ 3,() => Console.WriteLine("Case 3") }
}
...
replaceSwitch[value]();
这是一个非常微妙的转变,似乎并没有获得太多的收益,但实际上它好多了,好多了。如果你想知道为什么,这个blog post解释得很好。
如果方法类型是字符串,它有多个参数..例如,字符串emilvalid(字符串x1,字符串x2)和字符串regExp(字符串错误)..都返回字符串..你能告诉我如何要做到这一点......以及使用什么insted的行动..#行动只是无效的方法..和功能是返回的方法..但它仍然给错误.. – nikunjM