zoukankan      html  css  js  c++  java
  • C#泛型简化代码量示例

    泛型简化代码量

    下是我在项目中通过泛型来简化工作的一个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} 
    T= "{2}" ,id={3}", actor1.GetType(), actor1.Id, bullet1.GetType(), bullet1.Id);
            }
        }
    }

    程序的运行结果

    image

    IL代码如下

    image

  • 相关阅读:
    Centos 7 下安装LDAP 双主同步
    Apache Ranger && HDFS
    Java 学习(六)
    Java学习(五)
    Java学习(四)
    Java学习(三)
    Java学习(二)
    Java学习(一)
    css笔记
    磁盘性能测试方法
  • 原文地址:https://www.cnblogs.com/zhaoqingqing/p/3953363.html
Copyright © 2011-2022 走看看