具有类型约束或基类参数的泛型方法 [英] Generic method with type constraints or base class parameter
问题描述
据我所知,如果我编写一个接受从BaseClass
(或接口)派生的参数的方法,则有两种方法可以实现:
If I write a method accepting a parameter which derives from a BaseClass
(or an interface), as far as I know there are two ways to achieve that:
void MyMethod<T>(T obj) where T : BaseClass { ... }
和
void MyMethod(BaseClass obj) { ... }
使用一个相对于另一个有什么优点/缺点?
What advantages / disadvantages has using the one over the other?
推荐答案
在此示例中,两者之间没有太大区别,您可以访问方法中的相同成员,并且可以使用相同的派生类进行调用.在运行时会有所不同,因为针对每种类型调用的泛型方法都会被编译.
In this example there isn't a big difference between the two, you can access the same members inside the method and you can call it with the same derived classes. There is a runtime difference as a generic method is compiled for each type it is invoked with.
泛型有用的地方是如果您根据T
Where generics come in useful would be if you would return a value depending on T
使用泛型,您可以执行以下操作
With generics you could do the following
T MyMethod<T>(T obj) where T : BaseClass { ... }
MyMethod(derivedInstance).derivedProperty
没有这将是一个错误:
BaseClass MyMethod(BaseClass obj) { ... }
MyMethod(derivedInstance).derivedProperty // error
注意尽管您提到了约束基类,但值得一提的是,如果您约束的不是基类,而是接口,则通过结构中的结构实现额外的装箱操作.非通用版本,这可能会对性能产生严重影响.
Note Although you mention constraining to a base class, it is worth mentioning that if you constrain not to a class, but to an interface, extra boxing will occur if the implementation is by a struct in the non generic version, this can have severe performance implications.
这篇关于具有类型约束或基类参数的泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!