【问题标题】:Convert string to type & pass to generic delegate?将字符串转换为类型并传递给通用委托?
【发布时间】:2020-05-08 08:15:15
【问题描述】:

我对此困惑了一段时间,我确信有一个优雅的解决方案......我似乎找不到它。

我有一个 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 等。

我想我应该能够把它变成一个方法,它接受一个字符串和一个接受泛型类型的委托,但我被困在如何构造它上。谁能指出我正确的方向?

非常感谢

提姆

【问题讨论】:

  • 泛型参数需要在编译时知道。基本上你需要一个开关或字典等
  • 每个方法返回什么?很高兴看到minimal reproducible example
  • 感谢@MichaelRandall,我意识到我仍然需要一个开关,只是尽量不要多次重复相同的开关语句。感谢 Enigmativity,我是新海报,所以下次会做得更好!

标签: c# generics delegates


【解决方案1】:

就像 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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    相关资源
    最近更新 更多