【问题标题】:How to instantiate a generic type in base class?如何在基类中实例化泛型类型?
【发布时间】:2021-12-06 21:16:08
【问题描述】:

我构建了一个解析不同类型产品的 XML 解析器。解析器代码对所有产品类型都是通用的(它将 XML 反序列化为产品类型)

所以我创建了一个名为XmlParser的通用基类

public abstract class XmlParser<TProduct> where TProduct : ProductBase
{
    public abstract TEntity Instanciate();
        
    private string _parserName;

    public XmlParser(string parserName)
    {
        _parserName = parserName;
    }

    public List<TProduct>Parse()
    {
        TEntity product = Instanciate(); // <-- I need to instantiate the Generic type here 
        // deserialize XML into product
    }
}

还有一个派生类:

public class CarXmlParser : XmlParser<Car>
{
    public CarXmlParser() : base("CarParse") {}

    public override Car Instanciate()
    {
        return new Car();
    }
}

Car 是产品类型,派生自ProductBase

在基类中,我需要实例化TProduct。我能做到这一点的唯一方法是在基类中创建一个抽象方法:public abstract TEntity Instanciate();。显然孩子必须实现它。

有没有更简单的方法来实例化泛型类型?我已经看到this question 他们出于相同目的使用new T 约束,但是我无法将其应用于我的示例...

【问题讨论】:

    标签: c# generics inheritance


    【解决方案1】:

    如果它有一个默认构造函数,添加New Constraintnew

    新约束指定泛型类中的类型参数 声明必须有一个公共的无参数构造函数。要使用 新约束,类型不能是抽象的。

    示例

    public abstract class XmlParser<TProduct> 
        where TProduct : ProductBase, new()
    
    ...
    
    public List<TProduct>Parse()
    {
        var product = new TProduct();
    
        ...
    

    【讨论】:

      【解决方案2】:

      如果它没有new() 约束,您可以使用以下内容:

       Activator.CreateInstance<T>();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-03
        • 2011-04-02
        • 1970-01-01
        • 2013-09-18
        • 1970-01-01
        相关资源
        最近更新 更多