仅基于案例值调用方法的开关的替代方法 [英] Alternative for switch that only calls methods based on cases values

查看:52
本文介绍了仅基于案例值调用方法的开关的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有可能用一些较短的可读代码编写下一个开关?

Is there a possible way to write the next switch in some shorter, readable code?

switch (SomeValue)
{
  case "001": return DoMethod1(); break;
  case "002": return DoMethod2(); break;
  //etc..
}

我在想

Dictionary<string, Func<int>> MethodsByValue = new Dictionary<string, Func<int>>()
{
    { "001", DoMethod1 },
    { "002", DoMethod2 },
}

然后通过调用

return MethodsByValue[SomeValue]();

但这有可能吗?还是我在想办法走出困境.我找不到任何类似的提示,但是话又说回来,如果可能的话,我也不知道关键字.

But is this even possible? Or am I thinking way to far out of the box. I couldn't find anyting like this but then again, I don't know the keywords for this if it is possible.

要回答Lasse V. Karlsen的请求:

To answer the request of Lasse V. Karlsen:

这是我项目中代码的方式.在某些地方更改名称会导致原始名称无所谓,因为它使用的是我的母语.

This is how the code is in my project. Changed names at some places cause original names doesn't matter cause it is in my mother language.

public string GetRecord420(Dictionary<DataClass, object> dictionaryName)
{
  // some code here
}

public string GetRecord421(Dictionary<DataClass, object> dictionaryName)
{
  // some code here
}

//(Temperary) solution with the switch statement in a wrapper:
public string GetRecordByString(string s, Dictionary<DataClass, object> dictionaryName)
{
  switch (s)
  {
    case "320": return GetRecord420(dictionaryName);
    case "321": return GetRecord421(dictionaryName);
    default: return String.Empty;
  }
}

//How I hoped it could be, with a mapping dictionary.
public Dictionary<string, Func<string, Dictionary<DataClass, object>>> MethodByString = 
   new Dictionary<string, Func<string, Dictionary<DataClass, object>>>()
{
  { "320", GetRecord420 },
  { "321", GetRecord421 },
}

DataClass是一个Entity类,它存储一些列数据(列名,列类型等).

DataClass is an Entity class, which stores some column data (column name, column type, etc.).

我尝试了字典部分,但它给了我错误:无法从方法组转换为System.Func< ...>.

I tried the dictionary part, but it gives me the error: Cannot convert from method group to System.Func<...>.

更改为()=> GetRecord420给我一个错误:无法将lambda转换为委托类型System.Func< ...>,因为块中的某些返回类型不能隐式转换为委托返回类型.

Changing to () => GetRecord420 gives me the error: Cannot convert lambda to delegate type System.Func<...> because some of the return types in the block are not implicitly convertible to the delegate return type.

推荐答案

您的方法定义一定存在错误,

There must be an error with your method definitions,

class Program
{
    static void Main()
    {
       var methods = new Dictionary<string, Func<int>>
           {
               { "001", DoMethod1 }
           };
    }

    static int DoMethod1()
    {
        return 1;
    }
}

是完全有效的语法.

但是,由于1个引人注目的和1个主观原因,这并不比 switch 好.

but, this is not better than switch for 1 compelling and 1 subjective reason.

如果要与常量或文字进行比较,则应使用switch.这样,编译器就可以执行编译时间优化,而无需进行其他分析.

If you are comparing against constants or literals then you should use switch. This enables the compiler to peform compile time optimizations without additional analysis.

从主观上讲,字典/查找方法并不短,而且我觉得很难阅读.但是,在比较条件在运行时有所不同的情况下,这将很有用.

More subjectively, the dictionary/lookup approach is no shorter and I find it harder to read. However, it would be useful in situations where your comparison terms vary at runtime.

如果要避免将 switch 因子重写为函数.说,

If you want avoid rewriting the switch factor it into a function. Say,

Func<int> MethodsByValue(string value)
{
    switch(value)
    {
        case "001":
            return DoMethod1;

        default:
            return DoMethod2;
    }
}


无论哪种方式,

为什么不使用 enum 而不是使用一些字符串来枚举您的方法?然后,您将获得额外的性能和可读性优势.

Rather than using some arbritary strings to enumerate your methods, why not use an enum? Then you will get additional performance and readability benefits.

这篇关于仅基于案例值调用方法的开关的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆