加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 基类和泛型泛型之间的差异

发布时间:2020-12-15 08:44:17 所属栏目:百科 来源:网络整理
导读:我注意到一段时间后使用泛型,这与之间没有太大区别: public void DoSomethingT(T t) where T : BaseClass{} 还有这个: public void DoSomething(BaseClass t){} 到目前为止我唯一看到的区别是第一种方法可以添加其他约束,比如接口或new(),但如果你按照我编
我注意到一段时间后使用泛型,这与之间没有太大区别:
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被传入了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读