C# 中where关键字总结

where用于约束泛型

public class MyGenericClass<T> where T:IComparable { }

表示类型T只能是IComparable的子类

public class MyGenericClass <T> where T: IComparable, new()

new()只能出现在末尾
new()的意思就是说该类必须有公共的无参构造函数
————————————————
.NET支持的类型参数约束有以下五种:
where T : struct ---- T必须是一个值类型
where T : class ---- T必须是一个引用类型
where T : new() ---- T必须要有一个无参构造函数, (即他要求类型参数必须提供一个无参数的构造函数)
where T : NameOfBaseClass ---- T必须继承名为NameOfBaseClass的类
where T : NameOfInterface ---- T必须实现名为NameOfInterface的接口

public class MyClass<T,K,V,W,X>
        where T :struct           //约束T必须为值类型
        where K : class           //约束K必须为引用类型
        where V : IComparable     //约束V必须是实现了IComparable接口
        where W : K               //要求W必须是K类型,或者K类型的子类
        where X :class ,new ()    // X必须是引用类型,并且要有一个无参的构造函数(对于一个类型有多有约束,中间用逗号隔开)
 
    {
        ....
    }

————————————————
转载内容
原文链接:https://blog.csdn.net/qq_35097289/article/details/103969492
原文链接:https://blog.csdn.net/qq_42068856/article/details/101461974

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值