C#泛型简化代码量示例
发布时间:2021-05-21 06:58:38 所属栏目:大数据 来源: https://www.jb51.cc
导读:泛型简化代码量 下是我在项目中通过泛型来简化工作的一个Demo,记录一下: using System; using System.Collections.Generic; ? namespace MyCollection { public class CBase { private string id = "CBase" ; virtual string Id { get { return id; } set {
泛型简化代码量下是我在项目中通过泛型来简化工作的一个Demo,记录一下: using System;
using System.Collections.Generic;
? namespace MyCollection
{ public class CBase { private string id = "CBase"; virtual string Id { get { return id; }
set { id = value; }
} } ? class CActor : CBase
{ "CActor";
override return id; } set { base.Id = value; } } ? string resource;
} ? class CBullet : CBase
{ "CBullet";
value; }
} string effect;
} ? class GenericDemo
{ static CBullet MBullet = new CBullet(); static CActor MActor = new CActor(); static Dictionary<string,CBase> dict = new Dictionary<static T GetInfo<T>(string id) where T : CBase { CBase mBase; if (dict.TryGetValue(id,out mBase)) { return (T)mBase;
} return null; } 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);
} } } 程序的运行结果IL代码如下(编辑:北几岛) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |