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

Ger*_*ard 6 c# generics polymorphism

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

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

}
Run Code Online (Sandbox Code Playgroud)

还有这个:

public void DoSomething(BaseClass t){

}
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*kov 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);
 } 
Run Code Online (Sandbox Code Playgroud)

现在如果你同时打电话new Cat():

  • 两者的类型repeatGenericrepeatGenericVarIEnumerable<Cat> (注意var静态发现的类型,显示出突出的事实类型是静态已知)
  • 两者的类型repeatrepeatVar将是IEnumrable<Animal>尽管事实Cat是在过去.