C#中的where泛型约束介绍
泛型约束的意思就是说:类的泛型,只能是where字句后面所写的接口或类。
这么说好像也有点不大明白,举个例子。
我有一个接口,如下:
代码如下:
///
/// 国籍的接口
///
public interface INationality
{
string Nationality
{
set;
get;
}
string GetNationality();
}
///
/// 中国人
///
public class Chinese : INationality
{
private string _Nationality;
public string Nationality
{
set
{
_Nationality = value;
}
}
public string GetNationality()
{
return string.IsNullOrEmpty(_Nationality) ? "Default." : _Nationality;
}
}
///
/// 美国人
///
public class American : INationality
{
private string _Nationality;
public string Nationality
{
set { _Nationality = value; }
}
public string GetNationality()
{
return string.IsNullOrEmpty(_Nationality) ? "Default." : _Nationality;
}
}
///
///
///
///
public class PrintNationality where T : INationality, new()
{
T item = new T();
public void Print()
{
Console.WriteLine(string.Format("Nationality:{0}", item.GetNationality()));
}
}
由于有where字句的泛型约束,所以,创建PrintNationality的对象时,T的类型只能是继承子INationality接口的类。
代码如下:
public class Program
{
static void Main(string[] args)
{
PrintNationality _c = new PrintNationality();
PrintNationality _a = new PrintNationality();
//PrintNationality _o = new PrintNationality(); 此句是错误的,因为泛型类型必须是继承自INationality接口的类
_c.Print();
_a.Print();
Console.ReadKey();
}
}
以上的代码运行结果: