DotNet · 2015年11月5日

where(泛型类型约束)(C# 参考)

在泛型类型定义中,where 子句用于指定对下列类型的约束:这些类型可用作泛型声明中定义的类型参数的实参。 MyGenericClass,这样,类型参数 T 就可以实现 IComparable(Of T) 接口:

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

where 子句还可以包括基类约束,以指出某个类型必须将指定的类作为基类(或者就是该类本身),才能用作该泛型类型的类型参数。 这样的约束一经使用,就必须出现在该类型参数的所有其他约束之前。

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


where 子句还可以包括构造函数约束。 new() 的约束。 new() 约束可以让编译器知道:提供的任何类型参数都必须具有可访问的无参数(或默认)构造函数。 例如:

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


new() 约束出现在 where 子句的最后。

where 子句,例如:

interface IMyInterface
{
}

class Dictionary<TKey, TVal>
    where TKey : IComparable, IEnumerable
    where TVal : IMyInterface
{
    public void Add(TKey key, TVal val)
    {
    }
}


还可以将约束附加到泛型方法的类型参数,例如:

public bool MyMethod<T>(T t) where T : IMyInterface { }

请注意,对于委托和方法两者来说,描述类型参数约束的语法是一样的:

delegate T MyDelegate<T>() where T : new()

泛型委托。

类型参数的约束。

 

最新电影,电视剧,尽在午夜剧场

电影电视剧午夜不寂寞