泛型

解决拆装箱问题,使逻辑更加的严谨。

此前使用到的地方:游戏物体查找添加对象。

泛型类

我们可以定义一个类中出现的类型,类型事先不需要写死我们使用T来表示,这使得类的扩展性大大增加,可以应用于更多的场合。

class Program {
    static void Main(string[] args) {
        Data<string, bool> st = new Data<string, bool>();
    }
}
// 泛型类
class Data<T1, T2> {
    public T1 data1;
    public T2 data2;
}

泛型约束

class Program {
    static void Main(string[] args) {
        数据包<MonoBehaviour> list = new 数据包<MonoBehaviour>();
        list.DoProject(new Player());
    }
}

// 数据包类被约束到Component,只能出入Component当前类型或者Component派生的类型
class 数据包<T> where T : Component {
    public T 数据;
    public void DoProject<T>(T a) where T : Component {
        Console.WriteLine(a.transform);
    }
}

class Component {
    public Transform transform;
}

class Transform {

}

class MonoBehaviour : Component {

}

class Player : MonoBehaviour {

}
posted @   坞中客  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示