C#反射类的属性
以下例子是將HashTable對(duì)象反射成類(lèi)的實(shí)例,只是反射出了類(lèi)中的公共屬性。
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"); //加載程序集
//獲得對(duì)象類(lèi)型
??????????? Type type = assembly.GetType("StudyConsole.Student",true,true);
//獲取所有公有的屬性,不區(qū)分大小寫(xiě)s
??????????? PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
??????????? object student = Activator.CreateInstance(type); //創(chuàng)建實(shí)例
??????????? foreach (PropertyInfo field in properties)
??????????? {
??????????????? field.SetValue(student, data[field.Name], null);
??????????????? //Console.WriteLine("屬性類(lèi)型:{0},屬性值:{1}", field.PropertyType, field.Name);
??????????? }
??????? }
??? }
??? class Student
??? {
??????? public string Name { get; set; }
??????? public int Age { get; set; }
??????? public string Sex { get; set; }
??? }
}
轉(zhuǎn)載于:https://www.cnblogs.com/lansedehai1986/archive/2011/05/24/2056035.html
總結(jié)
- 上一篇: 将xap包嵌入到博客园中
- 下一篇: 系统讲解——更好的实施专案(Porjec