C#泛型的使用
C#泛型的使用
泛型介绍:泛型在Unity中用“T”表示,可以理解成占位符,他的主要目的就是代码复用。
简单举例:
我要处理图上两张表数据读取操作,以下是没用泛型写的
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 背包属性
///
public class KnapsackData
{
public int ID;
public int Count;
public int equipmentID;
}
分隔符-------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
///
/// 装备属性
///
public class EquipmentDate
{
public int equipmentID;
public string equipmentName;
public string equipmentUI;
}
分隔符-------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnapsackProxy
{
private List knapsacklList;
///
/// 构造函数
///
public KnapsackProxy()
{
knapsacklList = new List();
}
public void AddModel(KnapsackData model)
{
if (model == null)
{
Debug.LogError("参数不能为空");
}
this.knapsacklList.Add(model);
}
}
分隔符-------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EquipmentProxy
{
private List equipmentList;
///
/// 构造函数
///
public EquipmentProxy()
{
equipmentList = new List();
}
public void AddModel(EquipmentDate model)
{
if (model==null)
{
Debug.LogError("参数不能为空");
}
this.equipmentList.Add(model);
}
}
分隔符-------------------------------------------------------------------------------
你会发现这里有一个共同点,EquipmentProxy脚本与KnapsackProxy脚本只是数据类型不同,对数据的操作方式是完全相同的,这样的代码就叫冗余代码。这个时候就可以用到C#提供的泛型。新建一个父类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BaseProxy
{
private List tList;
///
/// 构造函数
///
public BaseProxy()
{
tList = new List();
}
public void AddModel(T model)
{
if (model == null)
{
Debug.LogError("参数不能为空");
}
this.tList.Add(model);
}
}
由子类去继承
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnapsackProxy:BaseProxy
{
}
分隔符-------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EquipmentProxy:BaseProxy
{
}