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);
        }
    }
}

程序的运行结果#

image

IL代码如下#

image

作者:赵青青   一名在【网易游戏】做游戏开发的程序员,擅长Unity3D,游戏开发,.NET等领域。
本文版权归作者和博客园共有,欢迎转载,转载之后请务必在文章明显位置标出原文链接和作者,谢谢。
如果本文对您有帮助,请点击【推荐】您的赞赏将鼓励我继续创作!想跟我一起进步么?那就【关注】我吧。
posted @   赵青青  阅读(637)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
阅读排行:
· 10亿数据,如何做迁移?
· 推荐几款开源且免费的 .NET MAUI 组件库
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 易语言 —— 开山篇
· Trae初体验
历史上的今天:
2013-09-03 Mecanim分析
2013-09-03 Mecanim 动作复用示例
CONTENTS
点击右上角即可分享
微信分享提示