【Unity&&C#】泛型约束和继承笔记

泛型约束

(1)引用类型约束:泛型必须是引用类型

public class AGenericClass<T> where T : class{……}

(2)值类型约束:泛型必须是值类型

public class AGenericClass<T> where T : struct{……}

(3)new约束:泛型必须包含无参构造方法(如与其他约束共用,则放在最后)

public class AGenericClass<T> where T : new(){……}

(4)类名约束:泛型必须是某类或派生自某类(与接口共用,则放在接口前方)

public class AGenericClass<T> where T : Person{……}

(5)接口约束:泛型必须实现一个或多个接口

public class AGenericClass<T> where T : IOne,ITwo,IThree{……}

(6)多泛型约束:有多个泛型

public class AGenericClass<T,B> where T : IOne where B: class{……}

泛型继承

拥有泛型约束的类作为父类,则其子类可以选择特化父类,或者使用与父类同样/更严格的约束

class MyClass{……}                                              

               ↓

class MyClassSon:MyClass{……}

public class AGenericClass<T> where T : MyClass

特化父类

public class MyTest : AGenericClass<MyClass>{……}

public class MyTest : AGenericClass<MyClassSon>{……}

使用与父类同样的约束

public class MyTest<B> : AGenericClass<B> where B:MyClass

使用比父类更严格的约束

public class MyTest<B> : AGenericClass<B> where B:MyClass,IOne

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Csharp泛型
{
    class Csharp泛型继承
    {

    }
    public class class1
    {
        
    }
    public class class1son : class1
    {

    }
    public class class2<T> where T: class1
    {
        public T a;
    }
    //特化父类
    public class class3 : class2<class1>
    {

    }
    //特化父类
    public class class4 : class2<class1son>
    {

    }
    //与父类相同约束
    public class class5<T> : class2<T> where T:class1
    {

    }
    //使用比父类更严格的约束
    public class class6<T>:class2<T> where T : class1,IAttack
    {

    }
    public interface IAttack
    {

    }
}

b站up视频链接(讲得很好):

【90 C#教程-泛型约束】 https://www.bilibili.com/video/BV1kP41197YV/?share_source=copy_web&vd_source=e09d10a3f6f91f4e730a7043a0df97a0

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值