プレイ反射-書き下ろしたプロパティ値を動的に取得する例

8522 ワード

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