我已经为此感到困惑了一段时间,并且我确定有一个优雅的解决方案……我似乎找不到它。
我有一个Web API,通过字符串参数设置要作用的对象类型。然后,我需要基于该类型调用许多通用方法。基本上,我所拥有的是一个很好的旧switch语句,我有不得不重复几次的危险,因此想尝试将其封装在可重用的方法中:
switch (ModuleName)
{
case "contacts":
return Method1<Contact>();
case "accounts":
return Method1<Account>();
default:
throw new Exception("ModuleName could not be resolved");
}
在其他地方,我需要做同样的事情,但调用Method2,Method3,Method4等。
我认为我应该能够将其转换为采用字符串和接受泛型类型的委托的方法,但是我仍然坚持如何构造它。谁能指出我正确的方向?
非常感谢
Tim
[就像迈克尔·兰德尔(Michael Randall)所说,泛型需要在编译时就知道。我认为您需要在这里重新考虑如何封装业务逻辑。您可能可以这样解决:
class Example{
void Main(){
var method1 = new LogicMethod1();
TestCase("contacts", method1);
TestCase("Case2", method1);
var method2 = new LogicMethod2();
TestCase("contacts", method2);
TestCase("Case2", method2);
}
void TestCase(string moduleName, LogicBase logic){
switch(moduleName){
case "contacts" : logic.DoTheStuff<Contact>(); break;
case "accounts" : logic.DoTheStuff<Account>(); break;
}
}
}
abstract class LogicBase{
public abstract void DoTheStuff<T>();
}
class LogicMethod1 : LogicBase{
public override void DoTheStuff<T>(){
//Logic for your Method1
}
}
class LogicMethod2 : LogicBase{
public override void DoTheStuff<T>(){
//Logic for your Method2
}
}