[C#基础学习]泛型 \<T>

泛型是在C++中就已经存在的功能,而C#也自然继承了这一个非常重要的功能。
定义方法:

  • class [ClassName]<泛型类型>
  • interface [InterfaceName]<泛型类型>
    泛型类型就相当于一个变量名字,用来代替当前未知类型的名字,所以可以是任何名字

泛型的名字可以是任意名字,只不过常用规范为T。

class Temp<T>
{
    public T value;
}
class Temp2<T1, T2, T3>
{
    T1 a;
    T2 b;
    T3 c;
}

调用时:

static void Main(string[] args)
{
    Temp<int> t = new Temp<int>();//一但决定类型后就不可改变
    t.value = ...;//赋值
    Temp2<int, string, bool>
}

接口也可以有泛型,和上述类似。

interface ITemp<T>
{
    T value{get;set;}
}

方法也可以有泛型

void swap<T>(ref T a, ref T b)
{
    T temp = a;
    a = b;
    b = temp;
}
// Start is called before the first frame update
void Start()
{
    string a = "1";
    string b = "2";
    swap<string>(ref a, ref b);
    Debug.Log(a+" "+b);
}

输出结果为

2 1

将输入类型改变为其他数据类型也一样能达到效果。

posted @ 2023-07-26 11:58  ComputerEngine  阅读(65)  评论(0编辑  收藏  举报