泛型方法:使用参数实例化泛型类型 [英] Generic method: instantiate a generic type with an argument

查看:637
本文介绍了泛型方法:使用参数实例化泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a generic method that takes in a type T, which i need to be able to call a constructor on that requires a single XmlNode. Currently, I am trying to do that by having an abstract base class that has the constructors I want (plus a parameterless one so i don't have to edit the "subclasses" other than to add the actual subclassing) and constraining by that. If i try to instantiate one of these classes, it complains that it:

Cannot create an instance of the variable type 'T' because it does not have the new() constraint

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

and if i add the new() constraint, i get:

'T': cannot provide arguments when creating an instance of a variable type

我该怎么办?

推荐答案

无法指定通用类型参数T应该具有带有指定参数的构造函数.基类的构造函数带有一些参数的事实无济于事,因为被覆盖的类不必必须具有相同的构造函数(例如,它可以使用一些值作为基类调用基构造函数.论点).

There is no way to specify that a generic type parameter T should have a constructor with a specified parameters. The fact that a base class has a constructor with some arguments doesn't help, because the overriden class doesn't have to have the same constructor (e.g. it can call the base constructor with some value as an argument).

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

The new() constraint can be used to require a parameter-less constructor only. I would probably suggest adding an interface constraint (e.g. IConstructFromXml) that would have a method to initialize the object - then you can call the method after you create the object using a parameterless constructor.

或者,您可以使用一个类型参数,表示用于创建指定类型的值的工厂.然后,您将创建工厂的实例,并使用它来创建所需类型的值.像这样:

Alternatively, you could take a type parameter representing a factory for creating values of the specified type. Then you would create an instance of the factory and use it to create the value of the type you need. Something like:

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>
   // ...
}

IFactory<T>界面如下所示:

interface IFactory<T> {
  T Create(XmlNode node);
}   

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

Calling the Foo method is a bit more involved in this version, because you have to explicitly specify the factory (and you need to implement it as well), but it may be closer to what you want...

这篇关于泛型方法:使用参数实例化泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆