泛型方法:使用参数实例化泛型类型

RCI*_*CIX 3 c# generics instantiation

我有一个采用T类型的通用方法,我需要能够在需要单个XmlNode的情况下调用构造函数。当前,我正在尝试通过具有一个抽象基类来实现此目的,该基类具有我想要的构造函数(加上一个无参数的构造函数,因此除了添加实际的子类之外,我无需编辑“子类”)并以此进行约束。如果我尝试实例化这些类之一,它会抱怨:

Cannot create an instance of the variable type 'T' because it does not have the new() constraint
Run Code Online (Sandbox Code Playgroud)

如果我添加new()约束,我得到:

'T': cannot provide arguments when creating an instance of a variable type
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

Tom*_*cek 5

无法指定通用类型参数T应具有带有指定参数的构造函数。一个基类有一些参数的构造函数的事实没有帮助,因为被覆盖的类不必须具有相同的构造(例如,它可以调用一些值作为参数基构造函数)。

new()约束只能用于要求无参数的构造函数。我可能会建议添加一个接口约束(例如IConstructFromXml),该接口约束应具有一个用于初始化对象的方法-然后,您可以在使用无参数构造函数创建对象后调用该方法。

或者,您可以使用代表工厂的类型参数来创建指定类型的值。然后,您将创建工厂的实例,并使用它来创建所需类型的值。就像是:

void Foo<TFactory, T>() where TFactory : IFactory<T> 
                        where TFactory : new() {
   var factory = new TFactory();
   T val = factory.Create(xmlNode); // Create method is defined in IFactory<T>
   // ...
}
Run Code Online (Sandbox Code Playgroud)

IFactory<T>界面看上去是这样的:

interface IFactory<T> {
  T Create(XmlNode node);
}   
Run Code Online (Sandbox Code Playgroud)

Foo在此版本中,调用该方法涉及更多,因为您必须显式指定工厂(并且也需要实现它),但是它可能更接近您想要的...