如何通过集合中的字符串值调用适当的方法? [英] How to call an appropriate method by string value from collection?
本文介绍了如何通过集合中的字符串值调用适当的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串集合.例如
I have a collection of strings. For example,
string[] coll={"1", "2", "3" ..."100"..."150"...}
并且我有相应的字符串收集方法,例如
and I have respective methods for the string collection such as
void Method1, void Method2, void Method100
我选择类似的方法:
string selector=string.Empty;
switch(selector)
{ case "1":
MethodOne();
break;
........
case "150":
Method150();
break;
}
上面的代码真的很无聊,我在字符串集合{"150" ..."250" ...}中将有更多的字符串元素.怎么做:
The above code is really bored and I will have more string elements in the string collection {"150" ... "250"...}. How to make like that:
string sel=col[55];
if(sel!=null)
// call here the respective method(method55)
我不想使用开关运算符,因为它会导致代码过多.
I do not want to use switch operator cause it gives rise to surplus of code.
推荐答案
您可以使用键和类似的动作声明字典
You can declare a dictionary with your keys and actions like
Dictionary<string, Action> actions = new Dictionary<string, Action>()
{
{ "1", MethodOne },
{ "2", ()=>Console.WriteLine("test") },
............
};
并将其调用为
actions["1"]();
PS:假设方法 void MethodOne(){}
在某处声明.
PS: Presuming method void MethodOne(){ }
is declared somewhere.
这篇关于如何通过集合中的字符串值调用适当的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文