C# 基类和连续泛型之间的区别

C# 基类和连续泛型之间的区别,c#,generics,polymorphism,C#,Generics,Polymorphism,在使用泛型一段时间后,我注意到这两者之间没有太大区别: public void DoSomething<T>(T t) where T : BaseClass{ } 到目前为止,我所看到的唯一区别是,第一个方法可以添加其他约束,如接口或new(),但如果您按照我编写的方式使用它,我看不出有多大区别。有人能指出关于选择其中一个的重要因素吗?我认为最明显的区别是方法中参数的类型将不同-在泛型情况下,实际类型,非泛型-始终基类 当需要调用其他泛型类/方法时,此信息非常有用 class

在使用泛型一段时间后,我注意到这两者之间没有太大区别:

public void DoSomething<T>(T t) where T : BaseClass{

}

到目前为止,我所看到的唯一区别是,第一个方法可以添加其他约束,如接口或
new()
,但如果您按照我编写的方式使用它,我看不出有多大区别。有人能指出关于选择其中一个的重要因素吗?

我认为最明显的区别是方法中参数的类型将不同-在泛型情况下,实际类型,非泛型-始终
基类

当需要调用其他泛型类/方法时,此信息非常有用

 class Cat : Animal {}

 void DoSomething<T>(T animal) where T:Animal
 {
    IEnumerable<T> repeatGeneric = Enumerable.Repeat(animal, 3);
    var repeatGenericVar = Enumerable.Repeat(animal, 3);
 } 
 void DoSomething(Animal animal)
 {
    IEnumerable<Animal> repeat = Enumerable.Repeat(animal, 3);
    var repeatVar = Enumerable.Repeat(animal, 3);
 } 
class猫:动物{}
无效剂量(T动物),其中T:动物
{
IEnumerable repeatGeneric=可枚举。重复(动物,3);
var repeatGenericVar=可枚举。重复(动物,3);
} 
无效剂量(动物)
{
IEnumerable repeat=可枚举重复(动物,3);
var repeatVar=可枚举。重复(动物,3);
} 
现在,如果使用
new Cat()调用这两个函数:

  • repeatGeneric
    repeatGenericVar
    的类型都将是
    IEnumerable
    (请注意,
    var
    静态查找类型,以突出显示静态已知的事实类型)
  • repeat
    repeatVar
    的类型都将是
    IEnumerable
    ,尽管传入了
    Cat

对于您的回答,我认为使用通用版本通常是一个更好的主意,这样您就可以保留有关该类型的更多信息。@Gerard-我不会说一个更好-它们有不同的用途和缺点。也就是说,泛型和继承通常会引起混淆:与
类My{}
以下类型
My
My
在某种程度上感觉相关,但它们只是两个独立的类型;由于开放性,通用方法的正确测试需要更多的案例:
voiddo(int)
需要测试一些
int
值,但是
voiddo(T)
需要测试一些值类型、参考类型;混合泛型和非泛型代码有时很难,特别是当泛型需要实类型时。。。
 class Cat : Animal {}

 void DoSomething<T>(T animal) where T:Animal
 {
    IEnumerable<T> repeatGeneric = Enumerable.Repeat(animal, 3);
    var repeatGenericVar = Enumerable.Repeat(animal, 3);
 } 
 void DoSomething(Animal animal)
 {
    IEnumerable<Animal> repeat = Enumerable.Repeat(animal, 3);
    var repeatVar = Enumerable.Repeat(animal, 3);
 }