蓝色的海1986

导航

C#反射类的属性

以下例子是将HashTable对象反射成类的实例,只是反射出了类中的公共属性。

using System.Reflection;

namespace StudyConsole
{
    class ReflectToObject
    {
        public static void ReflectToStudent()
        {
            Hashtable data = new Hashtable();
            data["Name"] = "李雷";
            data["Age"] = 25;
            data["Sex"] = "女";

            Assembly assembly = Assembly.Load("StudyConsole");  //加载程序集

    //获得对象类型
            Type type = assembly.GetType("StudyConsole.Student",true,true);

    //获取所有公有的属性,不区分大小写s
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            object student = Activator.CreateInstance(type);  //创建实例
            foreach (PropertyInfo field in properties)
            {
                field.SetValue(student, data[field.Name], null);
                //Console.WriteLine("属性类型:{0},属性值:{1}", field.PropertyType, field.Name);
            }

        }
    }

    class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
    }
}

posted on 2011-05-24 22:01  蓝色的海1986  阅读(434)  评论(0)    收藏  举报