简体   繁体   English

使用抽象类作为方法参数和约束到所述抽象类的泛型参数之间是否有任何明显的区别?

[英]Is there any appreciable difference between using an abstract class as a method parameter and generic parameter constrained to said abstract class?

Is there any major difference between using 使用之间有什么重大区别吗?

 public TValue SomeFunctionA<TValue>(BaseClass<TValue> bc)

over 过度

 public TValue SomeFunctionB<TValue, TBaseClass>(TBaseClass bc)
      where TBaseClass : BaseClass<TValue>

I've done some testing, and I can't seem to find any difference. 我做了一些测试,我似乎找不到任何区别。 All derived classes behave as they should (override something, new something, etc.). 所有派生类的行为都应该如此(覆盖某些东西,新东西等)。

What about if 'TValue' is known, such as (besides now you can use operators): 如果'TValue'是已知的,例如(除了现在你可以使用运算符):

 public int SomeFunctionAInt(BaseClass<int> bc)

and

 public int SomeFunctionBInt<TBaseClass>(TBaseClass bc)
      where TBaseClass : BaseClass<int>

In this case there is no difference. 在这种情况下,没有区别。 Generics are used to flow type information. 泛型用于传递类型信息。 As soon as you want to call other code, or return a value and that value must be statically typed to be the same as the input parameter bc , you need generics. 只要您想要调用其他代码,或者返回一个值,并且该值必须静态输入与输入参数bc相同,您需要泛型。

For example, the two functions below output the same thing, but the 2nd preserves type information: 例如,下面的两个函数输出相同的东西,但第二个保留类型信息:

object PrintAndReturn1(object obj) { Console.WriteLine(obj); return obj; }
T PrintAndReturn2<T>(T obj) { Console.WriteLine(obj); return obj; }

Generics come into play when you want to preserve type information. 当您想要保留类型信息时,泛型会发挥作用。 If you only ever consume a value and not pass it around, inheritance is enough. 如果你只是消耗一个值而不是传递它,继承就足够了。

You say you found no difference during testing. 你说在测试过程中没有发现任何差异。 This makes sense because the JIT erases the generic type information (mostly). 这是有道理的,因为JIT会删除泛型类型信息(主要是)。 The JITed code will look very similar for both variants. 两种变体的JITed代码看起来非常相似。 Virtual calls on references of a generic type are implemented the same way as non-generic v-calls. 对泛型类型的引用的虚拟调用以与非泛型v调用相同的方式实现。 (Note, that this goes for reference types only. All ref types share one JITed code body.) (注意,这只适用于引用类型。所有引用类型共享一个JITed代码体。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM