如何在 base class 中实例化泛型类型?

How to instantiate a generic type in base class?

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

所以我创建了一个名为 XmlParser

的通用基础 class
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
    }
}

和派生的 class:

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

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

Car 是产品类型,派生自 ProductBase

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

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

如果它有一个默认构造函数,添加New Constraint,然后new

The new constraint specifies that a type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

例子

public abstract class XmlParser<TProduct> 
    where TProduct : ProductBase, new()

...

public List<TProduct>Parse()
{
    var product = new TProduct();

    ...

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

 Activator.CreateInstance<T>();