【问题标题】:How to call an appropriate method by string value from collection?如何通过集合中的字符串值调用适当的方法?
【发布时间】:2015-08-20 08:58:09
【问题描述】:

我有一个字符串集合。例如,

string[] coll={"1", "2", "3" ..."100"..."150"...} 

我对字符串集合有各自的方法,例如

void Method1, void Method2, void Method100

我选择了这样的适当方法:

string selector=string.Empty;
switch(selector)
 { case "1": 
            MethodOne();
            break;
    ........
    case "150":
            Method150();
            break;
  }

上面的代码真的很无聊,我会在字符串集合{“150”...“250”...}中添加更多的字符串元素。 如何制作这样的:

 string sel=col[55];
 if(sel!=null)
        // call here the respective         method(method55)

我不想使用 switch 运算符,因为它会导致代码过剩。

【问题讨论】:

  • Dictionary<string,Action>
  • @Eser 写下你的答案,我会标记它。
  • @StepUp 你有类似的答案。最好接受它。
  • @Eser 我已经给出了答案。您的答案是较早的,也是第一个。这是公平的。

标签: c# .net-4.0 switch-statement console-application


【解决方案1】:

解决方案 1:

使用委托映射。这是更快的解决方案。

private static Dictionary<string, Action> mapping =
    new Dictionary<string, Action>
    {
        { "1", MethodOne },
        // ...
        { "150", Method150 }
    };

public void Invoker(string selector)
{
    Action method;
    if (mapping.TryGetValue(selector, out method)
    {
        method.Invoke();
        return;
    }

    // TODO: method not found
}

解决方案 2:

使用反射。这比较慢,并且仅适用于您的方法具有严格命名的情况(例如 1=MethodOne 150=Method150 将不起作用)。

public void Invoker(string selector)
{
    MethodInfo method = this.GetType().GetMethod("Method" + selector);
    if (method != null)
    {
        method.Invoke(this, null);
        return;
    }

    // TODO: method not found
}

【讨论】:

  • 您还可以结合这两种解决方案:拥有一个代表字典并使用反射填充它。这为您提供了解决方案 1 的效率,而不是像解决方案 2 那样重复代码。
【解决方案2】:

您可以使用您的键和操作声明字典,例如

Dictionary<string, Action> actions = new Dictionary<string, Action>()
{
    { "1", MethodOne },
    { "2", ()=>Console.WriteLine("test") },
    ............
};

并调用它

actions["1"]();

PS:假设方法void MethodOne(){ }在某处声明。

【讨论】:

  • 也许你知道如何调用“void MethodOne(int x)”?带参数的方法
  • @StepUp ()=&gt;MethodOne(i) ?可能先声明Dictionary&lt;string, Action&lt;int&gt;&gt;,然后再声明actions["1"](i)。取决于你的情况...
【解决方案3】:

你可以使用动态调用

 var methodName = "Method" + selector;
 var method = this.GetType().GetMethod(methodName);
 if (method == null)
 {
    // show error
 }
 else
    method.Invoke(this, null);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2010-11-20
    相关资源
    最近更新 更多