基类和泛型泛型之间的区别

时间:2014-01-30 08:03:42

标签: c# generics polymorphism

我注意到一段时间后使用泛型,这与之间差别不大:

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

}

和此:

public void DoSomething(BaseClass t){

}

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

1 个答案:

答案 0 :(得分:6)

我认为最明显的区别是方法内部参数的类型会有所不同 - 一般情况下实际类型,非泛型 - 总是BaseClass

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

 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);
 } 

现在,如果你同时使用new Cat()

  • repeatGenericrepeatGenericVar的类型将为IEnumerable<Cat>(请注意var静态查找类型,以突出显示事实类型已静态知道)
  • repeatrepeatVar的类型将IEnumrable<Animal>,尽管传递了Cat
相关问题