码迷,mamicode.com
首页 > 其他好文 > 详细

泛型使用Demo

时间:2014-09-03 13:00:56      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   使用   ar   

通过泛型来简化工作的一个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);
        }
    }
}

bubuko.com,布布扣

IL代码如下:

bubuko.com,布布扣

泛型使用Demo

标签:des   style   blog   http   color   os   io   使用   ar   

原文地址:http://www.cnblogs.com/zhaoqingqing/p/3953363.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!