C#基礎14:泛型

 

一、泛型類

  • 爲什麼需要泛型:你可能並不能確定當前某個變量到底應該是什麼類型,又或者說這個變量可以是任意一種類型
  • 泛型的定義:簡單來講就是“任意一種類型”
  • 泛型的應用:各種STL容器,Unity中的GetComponent<T>()
  • 符號:<佔位符1, 佔位符2…>

string.Format():C#歸一化,將指定的 String 中的格式項替換爲指定的 Object 實例的值的文本等效項,類似於C中的printf

一個泛型類的例子如下:非常簡單,可以直接看代碼

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CsharpTp : MonoBehaviour
{
    public class Person<A, B>           //A, B即爲泛型佔位符
    {
        private A aaa;
        private B bbb;
        public A Aaa { set { aaa = value; } }               //只可賦值,不可訪問
        public B Bbb { set { bbb = value; } }
        public void Show()
        {
            Debug.Log(string.Format("aaa={0}, bbb={1}", aaa, bbb));
        }
    }
    private void Start()
    {
        Person<string, int> p = new Person<string, int>();
        p.Aaa = "name";
        p.Bbb = 15;
        p.Show();

        Person<float, string> q = new Person<float, string> ();
        q.Aaa = 15.5f;
        q.Bbb = "name";
        q.Show();
    }
}

 

二、泛型方法

使用方法如下:

注意:如果當前方法所在類中,已經定義了這個泛型,方法名的後面就不需要再次定義

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CsharpTp : MonoBehaviour
{
    private void Start()
    {
        Debug.Log(Print<int>(15));
    }
    public T Print<T>(T a)
    {
        return a;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章