c# - 实例化一个知道公共(public)​​基类的泛型类型

标签 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?
    }

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

提前致谢

最佳答案

我真的没有在这里看到任何泛型,但看起来你想要:

return (CommonBaseClass) Activator.CreateInstance(DataTypes[type]);

如果您需要使用参数化构造函数,请使用 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]();
}

关于c# - 实例化一个知道公共(public)​​基类的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11161709/

相关文章:

c# - 展平 IEnumerable<IEnumerable<>>;理解泛型

c# - 在 WinForms 或 WPF 中构建 3d 曲线和绘图的控件

C# WPF-如果右键单击系统任务栏上的应用程序图标,则在关闭应用程序之前询问用户

c# - 如何在 visual studio 2015 中调试 amazon lambda 函数?

c# - 如何使 Visual Studio 将异常抛出到 NUnit gui 中?

c# - 如何在 EmguCV 中使用 C# 中的迭代器?

c# - where 子句中未使用 EFCore 枚举到字符串值的转换

c# - 创建特定数量的任务\线程后如何等待特定时间?

c# - 将方向应用到当前变换位置

c# - 使用 control.begininvoke 后 UI 仍然无响应