zoukankan      html  css  js  c++  java
  • 玩玩反射

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ReflectionTest
    {
        public class Employee
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    
    namespace ReflectionTest
    {
        public class GenericReflectionHelper<T>
        {
            public static List<string> GetListString(List<T> srcList, Dictionary<string, string> keyDict)
            {
                string row = string.Empty;
                int i = 0;
                List<string> result = new List<string>();
                foreach (T elem in srcList)
                {
                    Type type = elem.GetType();
                    row = string.Empty;
                    i = 0;
                    foreach (KeyValuePair<string, string> dictElem in keyDict)
                    {
                        PropertyInfo propertyInfo = type.GetProperty(dictElem.Key);
                        string rowValue = propertyInfo.GetValue(elem, null).ToString();
                        if (i == 0)
                            row += dictElem.Value + ": " + rowValue;
                        else
                            row += ", " + dictElem.Value + ": " + rowValue;
    
                        i++;
                    }
    
                    result.Add(row);
                }
    
                return result;
            }
        }
    }

    call method:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ReflectionTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<Employee> employees = new List<Employee>();
                employees.Add(new Employee { Name = "David", Age = 33 });
                employees.Add(new Employee { Name = "Neil", Age = 34 });
                employees.Add(new Employee { Name = "Tony", Age = 27 });
    
                Dictionary<string, string> dict = new Dictionary<string, string>();
                dict.Add("Name", "姓名");
                dict.Add("Age", "年龄");
    
                List<string> result = GenericReflectionHelper<Employee>.GetListString(employees, dict);       
                foreach(string row in result)
                    Console.WriteLine(row);
            }
        }
    }

    运行结果:
    姓名: David, 年龄: 33
    姓名: Neil, 年龄: 34
    姓名: Tony, 年龄: 27

  • 相关阅读:
    python的内置方法 isinstance && issubclass
    python类的内置方法
    反射(python内置方法)
    类装饰器 @property
    多态与多态性
    组合(对象1.属性=对象2)
    类的封装
    多继承 mro 继承顺序 与 菱形继承(钻石继承)
    类的继承派生&&重写
    封装 继承 多态 派生 组合定义 && 对象之间交互
  • 原文地址:https://www.cnblogs.com/davidgu/p/3337744.html
Copyright © 2011-2022 走看看