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

  • 相关阅读:
    微信开发返回验证来源方式代码
    Yii 开发过程 tips
    PHP 搜索分词实现代码
    PHP 中文字符串截取
    Ubuntu16.04设置静态ip
    Linux(Ubuntu18.04)安装Chrome浏览器
    ubuntu18.04安装redis
    ubuntu18.04虚拟机安装docker
    虚拟机安装ssh,关闭防火墙
    面试送命题,你为什么从上家公司离职?(面试题总结大全)
  • 原文地址:https://www.cnblogs.com/davidgu/p/3337744.html
Copyright © 2011-2022 走看看