有没有可能用更短、可读的代码编写下一个开关?
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<...> 因为块中的某些返回类型不能隐式转换为委托返回类型。