
public voID DoSomething<T>(T t) where T : BaseClass{} 还有这个:
public voID DoSomething(BaseClass t){} 到目前为止我唯一看到的区别是第一种方法可以添加其他约束,比如接口或new(),但如果你按照我编写它的方式使用它,我看不出太多区别.任何人都可以指出选择一个或另一个的重要因素吗?
解决方法 我认为最明显的区别是方法内部的参数类型会有所不同 – 在通用情况下实际类型,非泛型 – 总是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); } 现在如果你用新的Cat()调用它们:
> repeatGeneric和repeatGenericVar的类型将是IEnumerable< Cat> (注意var静态查找类型,显示突出显示事实类型是静态已知的)> repeat和repeatvar的类型将是IEnumrable< Animal>尽管Cat被传入了.
总结以上是内存溢出为你收集整理的c# – 基类和泛型泛型之间的差异全部内容,希望文章能够帮你解决c# – 基类和泛型泛型之间的差异所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)