【发布时间】:2011-12-04 10:58:27
【问题描述】:
我想知道您是否可以创建包含方法的数组或列表。我不想使用 switch 或大量 if 语句。
谢谢
【问题讨论】:
我想知道您是否可以创建包含方法的数组或列表。我不想使用 switch 或大量 if 语句。
谢谢
【问题讨论】:
是的,可以有这样的数组或列表。根据输入或输出参数的数量,您可以使用类似
List<Func<T1, T2, TReturn>>
Func<T1, T2, TReturn> 类型的实例是类似的方法
TReturn MyFunction(T1 input1, T2 input2)
【讨论】:
给你
List<Action> list = new List<Action>();
list.Add( () => ClassA.MethodX(paramM) );
list.Add( () => ClassB.MethodY(paramN, ...) );
foreach (Action a in list) {
a.Invoke();
}
【讨论】:
Invoke() 在这里?你就不能a()吗?
a()。而且您不需要为此使用沉重的List<T>。你可以做new Action[] { ()=> MyMethod(), ()=> MyMethod2() };
如果你不想使用列表,也许你想试试这个
public Action[] methods;
private void methodsInArray()
{
methods= new Action[2];
methods[0] = test ;
methods[1] = test1;
}
private void test()
{
//your code
}
private void test1()
{
//your code
}
【讨论】:
如果您尝试替换开关,那么字典可能比列表更有用
var methods = new Dictionary<string, Action>()
{
{"method1", () => method1() },
{"method2", () => method2() }
};
methods["method2"]();
我认为这和 switch 语句是一种代码味道,它们通常可以是 replaced by polymorphism。
【讨论】: