泛型约束的意思就是说:类的泛型,只能是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();
}
}
以上的代码运行结果: