C#泛型的使用

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
{

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

芊泽散人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值