有没有可能用一些更短、更易读的代码来编写下一个开关?
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]();
但这甚至可能吗?还是我在想办法开箱即用。我找不到任何这样的东西,但话又说回来,如果可能的话,我不知道这个关键字。
编辑:回答 Lasse V. Karlsen 的要求:
这就是我的项目中的代码。在某些地方更改名称会导致原始名称无关紧要,因为它是我的母语。
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类,里面存储了一些列数据(列名、列类型等)。
我尝试了字典部分,但它给了我错误:无法从方法组转换为 System.Func<...>。
更改为 () => GetRecord420 给我错误:无法将 lambda 转换为委托类型 System.Func<...> 因为块中的某些返回类型不能隐式转换为委托返回类型。