C#知识:泛型及泛型约束
对于泛型,以前接触的比较多的还是泛型容器,有时候也会自定义泛型容器。除此之外,C#很多内置方法都是泛型方法,掌握泛型很重要。
1、泛型
- 用占位符暂代类型
- 是类型的参数化
- 包括泛型类、泛型接口、泛型方法
- 在定义类、接口或者方法时用占位符代表类型
- 在类实例化、实现接口或调用方法时传递具体类型
1.1 作用:
- 避免了频繁装箱拆箱,提高效率
- 提高了类型安全性
1.2 使用场景:
- 在对不同类型的数据进行相同的逻辑处理时用泛型
1.3 泛型类
- 继承泛型类时必须传递具体类型
class GenericClass<T>
{
public T value;
}
class Grandpa<T>
{
public T value;
}
class Father<T,K>:Grandpa<int>
{
public new T value;
}
//子类不含无参构造
class Son:Father<int, string>
{
public new int value;
public Son(int value)
{
this.value = value;
}
}
GenericClass<float> genericClass = new GenericClass<float>();
genericClass.value = 2.1f;
1.4 泛型接口
- 实现泛型接口时必须传递具体类型
interface IGeneric<T>
{
public T ModelFunc();
}
class SonOfInterface : IGeneric<int>
{
public int value;
public int ModelFunc()
{
return 1

最低0.47元/天 解锁文章
3729

被折叠的 条评论
为什么被折叠?



