C# where

在C#中,用where来约束泛型参数。能使用的大概有以下几种类型:

  • where T : struct:泛型参数<T>必须是值类型(struct或者enum
  • where T : class:泛型参数<T>必须是引用类型
  • where T : new():泛型参数<T>必须有默认构造函数。要注意的是如果有多个约束,这一个必须放在最后。
  • where T : NameOfBaseClass:泛型参数<T>必须NameOfBaseClass类的本身或者子类。
  • where T : NameOfBaseInterface:泛型参数<T>必须实现了NameOfBaseInterface接口。

具体可以看看下面的代码。

值类型和引用类型的约束:

C#
class MyClass<T, U>
    where T : class
    where U : struct
{ }

接口,默认构造函数的约束:

C#
public class MyGenericClass<T> where T : IComparable, new()
{
    // The following line is not possible without new() constraint:
    T item = new T();
}

多个约束

C#
interface IMyInterface:
{
}

class Dictionary<TKey, TVal>
    where TKey : IComparable, IEnumerable
    where TVal : IMyInterface
{
    public void Add(TKey key, TVal val)
    {
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值