C#泛型约束
常见的泛型约束:基类约束,接口约束,构造函数约束,引用类型约束,值类型约束,泛型参数约束等
泛型约束的定义
泛型约束是编程语言中限制泛型类型参数的机制,允许开发者指定泛型参数必须满足的条件(如继承特定类、实现接口或拥有无参构造函数)。泛型约束通过增加类型安全性,减少运行时错误。
泛型约束的优势
- 编译时类型检查:提早发现类型不匹配问题
- 增强代码可读性:明确泛型参数的预期行为
- 启用特定操作:如调用约束类型的方法或构造函数
约束的注意事项
- 约束不能是密封类(如
string
)或静态类。 - 值类型约束(
struct
)与无参构造函数约束(new()
)不能同时使用,因为所有值类型隐式包含无参构造函数。
1.基类约束(where T : 基类)
where T : Product
示例:
public class Animal{public string name { get; set;}
}
public class MyClass<T> where T : Animal
{public T testValue;
}
//这就是基类的约束,使用MyClass数组的时候,泛型中的变量类型就只能使用Animal类或Animal类的派生类
2.接口约束(where T : 接口)
注意:制定类型参数必须是实现了特定接口的才可以
where T : IComparable<T>
示例:
public interface IComparable<T> //接口
{int CompareTo(T other);
}
public class Person : IComparable<Person> //实现接口的类
{public int CompareTo(Person other){return 1;}
}
public class MyCompare<T> where T : IComparable<T>
{public void Success(){Console.WriteLine("实现了约束接口的类");}
}
//表示当前泛型类型使用的时候只能传入,实现了接口类的class类型
3.构造函数约束(where T : new())
注意:参数必须具有无参的公共构造函数
where T : new()
public class Product
{public string Name {get;set;}public Product(){Console.WriteLine("类中必须要有的无参构造函数")}
}
//构造函数约束使用new()
public class MyClass<T> where T : new()
{public T obj {get;set;}
}
//表示当前泛型类型使用的时候只能传入,有无参构造函数的类型
//多个约束,必须是Product的构造函数才可以使用
public class MyClass<T> where T : Product,new()
{public T obj {get;set;}
}
//表示当前泛型类型使用的时候只能传入,Product类型
4.引用类型约束(where T : class)
注意:制定参数必须是引用类型
where T : class
public class MyClass<T> where T : class
{public T testValue {get;set;}
}
//表示当前泛型类型使用的时候只能传入,class类型
5.值类型约束(where T : struct)
注意:指定类型必须是值类型
where T : struct
public class MyClass<T> where T : struct
{public T testValue {get;set;}
}
//表示当前泛型在使用的时候只能传入,值类型
6.泛型参数约束(where T : U)
注意:指定参数必须从参数U派生
public class Animal{public string name { get; set;}
}
public class MyClass<T> where T : Animal
{public T testValue;
}
//这就是基类的约束,使用MyClass数组的时候,泛型中的变量类型就只能使用Animal类或Animal类的派生类