ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Unity C#进阶案例 “泛型编程”

2026/8/10 9:54:36 拓冰建站 浏览量
Unity C#进阶案例 “泛型编程”

文章目录

      • 泛型基础
      • 示例1:泛型类与方法
      • 示例2:泛型方法
      • 示例3:泛型约束
      • 示例4:泛型委托与事件
      • 示例5:泛型单例模式(Unity)

在Unity中,C#的泛型编程是一种强大的工具,它允许你编写可复用且类型安全的代码。以下将详细讲解泛型,并通过五个代码实例来展示其在Unity中的实际应用。

泛型基础

什么是泛型?
泛型是C#中的一种特性,它允许你在定义类、接口、方法或委托时,指定一个或多个类型参数。这些类型参数在编译时由实际的类型替换,从而创建特定类型的实例。这样可以确保数据类型的一致性,并避免不必要的装箱和拆箱操作,提高性能和安全性。

例如:

public class MyGenericClass<T>
{public T Value { get; set; }
}

在这个例子中,T是一个类型参数,当创建MyGenericClass<int>MyGenericClass<string>等实例时,T会被具体的数据类型替代。

示例1:泛型类与方法

场景:一个通用容器类,用于存储任意类型的数据。

// 定义泛型类
public class DataContainer<T>
{private T data;public void SetData(T value){data = value;}public T GetData(){return data;}
}// 使用
var intContainer = new DataContainer<int>();
intContainer.SetData(42);
int number = intContainer.GetData(); // number 现在是 42var stringContainer = new DataContainer<string>();
stringContainer.SetData("Hello, World!");
string message = stringContainer.GetData(); // message 现在是 "Hello, World!"

示例2:泛型方法

场景:一个交换两个变量值的方法,适用于任何引用类型或值类型。

public static class Utilities
{// 泛型方法public static void Swap<T>(ref T a, ref T b){T temp = a;a = b;b = temp;}
}// 使用
int x = 10, y = 20;
Utilities.Swap(ref x, ref y); // 交换后,x=20, y=10string first = "Alice", second = "Bob";
Utilities.Swap(ref first, ref second); // 交换后,first="Bob", second="Alice"

示例3:泛型约束

场景:一个泛型类需要限制只能处理实现了某个接口的类型。

public interface IComparable<T>
{int CompareTo(T other);
}public class SortableList<T> where T : IComparable<T>
{private List<T> list = new List<T>();public void Add(T item){list.Add(item);}public void Sort(){list.Sort((a, b) => a.CompareTo(b));}
}// 使用
class CustomType : IComparable<CustomType>
{public int CompareTo(CustomType other){// 实现比较逻辑}// ...
}SortableList<CustomType> customList = new SortableList<CustomType>();
customList.Add(new CustomType());
customList.Sort();

示例4:泛型委托与事件

场景:一个通用事件处理器,接受任何类型的参数。

public delegate void GenericEventHandler<T>(object sender, T args);public class EventManager
{public event GenericEventHandler<string> OnStringEvent;public event GenericEventHandler<Vector3> OnVector3Event;public void RaiseStringEvent(string message){OnStringEvent?.Invoke(this, message);}public void RaiseVector3Event(Vector3 position){OnVector3Event?.Invoke(this, position);}
}// 使用
EventManager manager = new EventManager();manager.OnStringEvent += (sender, message) => Debug.Log($"String event: {message}");
manager.OnVector3Event += (sender, position) => Debug.Log($"Vector3 event: {position}");manager.RaiseStringEvent("Hello");
manager.RaiseVector3Event(new Vector3(1, 2, 3));

示例5:泛型单例模式(Unity)

场景:创建一个可以在Unity中重用的泛型单例类。

public class Singleton<T> : MonoBehaviour where T : Singleton<T>
{protected static T _instance;public static T Instance{get{if (_instance == null){_instance = FindObjectOfType<T>();if (_instance == null){GameObject obj = new GameObject(typeof(T).Name);_instance = obj.AddComponent<T>();}}return _instance;}}protected virtual void Awake(){if (_instance != this){Destroy(gameObject);return;}DontDestroyOnLoad(gameObject);}
}// 使用
public class GameManager : Singleton<GameManager>
{// 游戏管理器的具体实现...
}

以上五个示例展示了泛型在Unity项目中的不同应用场景,从简单的数据容器到复杂的事件处理和设计模式实现。通过使用泛型,可以有效减少重复代码,增强代码的灵活性和可扩展性。

python推荐学习汇总连接:
50个开发必备的Python经典脚本(1-10)

50个开发必备的Python经典脚本(11-20)

50个开发必备的Python经典脚本(21-30)

50个开发必备的Python经典脚本(31-40)

50个开发必备的Python经典脚本(41-50)
————————————————

​最后我们放松一下眼睛
在这里插入图片描述