Dynamic .NET动态决定调用类似类?

Dynamic .NET动态决定调用类似类?,dynamic,reflection,Dynamic,Reflection,C#在.NET 4.5上: public Interface IMyInterface { public string DoSomething( string input1 ) } public MyClass1 : IMyInterface { public string DoSomething( string input1 ) { return "1"; } } public MyClass2 :

C#在.NET 4.5上:

 public Interface IMyInterface
    {
    public string DoSomething( string input1 )
    }

    public MyClass1 : IMyInterface
    {
    public string DoSomething( string input1 )
    {
    return "1";
    }
    }

    public MyClass2 : IMyInterface
    {
    public string DoSomething( string input1 )
    {
    return "2";
    }
    }
在运行时,我想检测托管环境,设置某种“全局”,然后基于全局始终实例使用MyClass1或MyClass2。我不希望有一个“MyClass”,然后在其中执行大量的案例逻辑来检测环境

这样做的好模式或做法是什么?这真的是一个动态的好地方吗


谢谢

似乎您需要使用Factory。在Factory类中创建一个方法以返回MyClass对象。将方法的返回类型保持为
IMyInterface
。在该方法中,可以执行宿主逻辑,并根据宿主逻辑的输出实例化适当的类并返回对对象的引用