实例化知道公共基类的泛型类型

jim*_*les 1 c#

我试图完成一些看似有点复杂但在我的情况下会非常有用的东西,看起来像这样.

    public class CommonBaseClass {}
    public class Type1Object : CommonBaseClass {}
    public class Type2Object : CommonBaseClass {}
    public class Type3Object : CommonBaseClass {}

    public static Dictionary<string, Type> DataTypes = new Dictionary<string, Type>()
    {
        { "type1" , typeof(Type1Object) },
        { "type2" , typeof(Type2Object) },
        { "type3" , typeof(Type3Object) }
    };

    public static CommonBaseClass GetGenericObject(string type)
    {
        return new DataTypes[type]();     //How to instantiate generic class?
    }
Run Code Online (Sandbox Code Playgroud)

因为我可以保证所有构造函数具有相同的签名,我知道这将起作用,只是不确定如何让编译器知道.

提前致谢

Jon*_*eet 6

我在这里看不到任何泛型,但它看起来像你想要的:

return (CommonBaseClass) Activator.CreateInstance(DataTypes[type]);
Run Code Online (Sandbox Code Playgroud)

如果需要使用参数化构造函数,请使用替代的重载Activator.CreateInstance.

或者,考虑将您的字典更改为代表:

private static Dictionary<string, Func<CommonBaseClass>> DataTypes =
    new Dictionary<string, Func<CommonBaseClass>>
    {
        { "type1", () => new Type1Object() }
        { "type2", () => new Type2Object() },
        { "type3", () => new Type3Object() }
    };

public static CommonBaseClass GetGenericObject(string type)
{
    return DataTypes[type]();
}
Run Code Online (Sandbox Code Playgroud)