zoukankan      html  css  js  c++  java
  • 头脑风暴之 反射+泛型 构建 普通通用功能

    地球人都知道 构建通用的功能 泛型和反射是必不可少的,然后现在很多人都用ORM实体框架+泛型也可以构建

    但其内部也是通过反射实现的。

    解开迷雾 见天日吧。

    ---c#代码

     public class Boy
        {
            public int BoyId { get; set; }
            public string BoyName { get; set; }
        }
    
        public class Girl
        {
            public int GirlId { get; set; }  
            public string GirlName { get; set; }
        }
        class Program
        {
            static IDictionary<object, object> GetList<T>()  where T : class
            {
                Type modelType = typeof(T);
                //创建T对象
                T model = (T)Activator.CreateInstance(modelType);
                //T model = Activator.CreateInstance<T>();
                Type t = model.GetType();
                //获取T对象的所有属性
                PropertyInfo[] props = t.GetProperties();
                //将属性名称作为key,属性值作为value
                Dictionary<object, object> dict = new Dictionary<object, object>();
                foreach (PropertyInfo prop in props)
                {
                    //获取属性的名称
                    string propName = prop.Name;
    
                    //为model对象的pro属性设置值
                    //如果此属性类型是int就赋值10
                    if (prop.PropertyType==typeof(Int32))
                    {   //在实际开发中 一般用 DataRow获取数据库相应的字段值如 dr[propName]
                        prop.SetValue(model, 10, null);
                    }
                    else //如果此属性类型 不是 int就统一赋值"aaa"
                    {
                        prop.SetValue(model, "aaa", null);
                    }
                    //获取model中是属性值
                    object propValue=prop.GetValue(model, null);
                    dict.Add(propName,propValue.ToString());
                }
                return dict;
            }
            static void Main(string[] args)
            {
    
                foreach (var item in GetList<Boy>())
                {
                    Console.WriteLine(item.Key+":"+item.Value);
                }
                Console.WriteLine("success");
                Console.ReadKey();
            }
        }

    ---运行结果

    ---泛型约束
     
     
  • 相关阅读:
    Django tutorial part2
    Django tutorial part1
    webpy使用mysql数据库操作(web.database)
    Sicily 1031. Campus 解题报告
    Sicily 1321. Robot 解题报告
    Sicily 1940. Ordering Tasks 解题报告
    Sicily 1936. Knight Moves 解题报告
    Java多线程21:多线程下的其他组件之CyclicBarrier、Callable、Future和FutureTask
    Java多线程20:多线程下的其他组件之CountDownLatch、Semaphore、Exchanger
    Java多线程19:定时器Timer
  • 原文地址:https://www.cnblogs.com/zjflove/p/2849508.html
Copyright © 2011-2022 走看看