将字符串转换为类型并传递给通用委托?
Convert string to type & pass to generic delegate?
我对此困惑了一段时间,我确信有一个优雅的解决方案...我似乎找不到它。
我有一个 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 等。
我想我应该能够将其转换为一个方法,该方法采用一个字符串和一个接受泛型类型的委托,但我对如何构造它感到困惑。谁能指出我正确的方向?
非常感谢
蒂姆
正如 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
}
}
我对此困惑了一段时间,我确信有一个优雅的解决方案...我似乎找不到它。
我有一个 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 等。
我想我应该能够将其转换为一个方法,该方法采用一个字符串和一个接受泛型类型的委托,但我对如何构造它感到困惑。谁能指出我正确的方向?
非常感谢
蒂姆
正如 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
}
}