C#泛型简化代码量示例
本文为作者原创,转载请注明出处:https://www.cnblogs.com/zhaoqingqing/p/3953363.html
泛型简化代码量#
下是我在项目中通过泛型来简化工作的一个Demo,记录一下:
using System;
using System.Collections.Generic;
namespace MyCollection
{
public class CBase
{
private string id = "CBase";
public virtual string Id
{
get { return id; }
set { id = value; }
}
}
public class CActor : CBase
{
private string id = "CActor";
public override string Id
{
get { return id; }
set { base.Id = value; }
}
public string resource;
}
public class CBullet : CBase
{
private string id = "CBullet";
public override string Id
{
get { return id; }
set { base.Id = value; }
}
public string effect;
}
public class GenericDemo
{
public static CBullet MBullet = new CBullet();
public static CActor MActor = new CActor();
public static Dictionary<string, CBase> dict = new Dictionary<string, CBase>();
public static T GetInfo<T>(string id) where T : CBase
{
CBase mBase;
if (dict.TryGetValue(id, out mBase))
{
return (T)mBase;
}
return null;
}
public static void Main(string[] args)
{
//dict = new Dictionary<string, CBase>();
dict.Add("actor", MActor);
dict.Add("bullet", MBullet);
CActor actor1 = GetInfo<CActor>("actor");
CBullet bullet1 = GetInfo<CBullet>("bullet");
Console.WriteLine("T= \"{0}\" ,id={1} \nT= \"{2}\" ,id={3}", actor1.GetType(), actor1.Id, bullet1.GetType(), bullet1.Id);
}
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 10亿数据,如何做迁移?
· 推荐几款开源且免费的 .NET MAUI 组件库
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 易语言 —— 开山篇
· Trae初体验
2013-09-03 Mecanim分析
2013-09-03 Mecanim 动作复用示例