首页 > 代码库 > 泛型使用Demo
泛型使用Demo
通过泛型来简化工作的一个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);
}
}
}
IL代码如下:
泛型使用Demo
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。