通用方法问题... [英] generic method question...............
问题描述
我目前正在尝试实现通用方法:
I am currently trying to implement a generic method:
public int Save<T>(DomainObject model) where T : BaseConfig
{
...
}
T是实现BaseConfig的一种类型.我需要能够在Save方法中实例化一个通过类型T的新类.
BaseConfig类在实例化时填充其自己的配置值.
因此,在通用的Save方法中,我需要说一些类似的内容:T config = new T()
我很确定上面提供的实例化代码不是正确的实现方式,但是我认为这很好地说明了我要实现的目标.
因此,您可以建议实现此设计的最佳方法吗?
T is a type of class that implements BaseConfig. I need to be able to instantiate a new class of the passed type T in the Save method.
The BaseConfig class populates it''s own config values upon instantiation.
So within the generic Save method I need to say something like: T config = new T()
I''m pretty sure that the instantiation code that I provided above is not the correct way to do it but I think it''s a pretty good illustration of what I''m trying to achieve.
So can you advise on the best way to implement this design?
推荐答案
这不是使用泛型的好方法.在您的示例中,在类实现中未使用T
,但这是关键.如果操作正确,则不需要键入case.
有很多设计方法可以达到目的.在某些情况下,您需要将OOP与泛型结合使用.一些想法:
您还可以在DomainObject
中使用通用方法,然后使用T
类型实例化这些方法.
作为上述方法的一种变体,您可以使整个DomainObject
类通用,并使用T
对其进行实例化.
您可以将接口IConfig
而不是BaseConfig
设置为DomainObject
已知.DomainObject
的实例化将仅定义IConfig
的实现;DomainObject
仅与接口一起使用,但与在通用实例化时定义的接口实现方式无关.
如果我可以了解有关您的应用程序和预期设计的更多信息,我会建议其他事项,但是您需要显示一些基本方法并解释它们应该做什么. (算法优先!")
—SA
It is not a good way of using generic. In your sample there is not use ofT
in the class implementation, but this is a key. If you do it correctly, type case is not needed.
There are many design way to achieve the results. In some cases you need to combine OOP with generics. Some ideas:
You can also have generic methods inDomainObject
, then you will instantiate those methods withT
type.
As a variant of the above you can make wholeDomainObject
class generic and instantiate it withT
.
You can make an interfaceIConfig
instead ofBaseConfig
and make it known toDomainObject
. Instantiation ofDomainObject
will define only the implementation ofIConfig
;DomainObject
will work with interface only but agnostic about its implementation defined at the moment of generic instantiation.
If I could learn more about your application and intended design, I would advise something else, but you need to show some essential methods and explain what they are supposed to do. ("Algorithms first!")
—SA
只是将new()约束添加到方法中,以指定该类具有无参数的构造函数.没有它,编译器错误是无法创建变量类型"T"的实例,因为它没有new()约束".
Hi,
Just to add the new() constraint to the method to specify that the class has a parameterless constructor . Without it the compiler error is "Cannot create an instance of the variable type ''T'' because it does not have the new() constraint".
public int Save<T>(DomainObject model) where T : BaseConfig, new() {
T config = new T();
return 0;
}
艾伦.
我是否正确理解了这个问题?
Alan.
have I understood the question correctly?
这将在您的方法中起作用吗?
Will this work inside your method?
T realType = model as T;
编辑==========
我将"obj"更改为"model".
EDIT ==========
I changed "obj" to "model".
这篇关于通用方法问题...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!