- 論壇徽章:
- 0
|
- 以下例子是將HashTable對(duì)象反射成類的實(shí)例,只是反射出了類中的公共屬性。
-
-
using System.Reflection;
-
-
namespace StudyConsole
-
{
-
class ReflectToObject
-
{
-
public static void ReflectToStudent()
-
{
-
Hashtable data = new Hashtable();
-
data["Name"] = "李雷";
-
data["Age"] = 25;
-
data["***"] = "女";
-
-
Assembly assembly = Assembly.Load("StudyConsole"); //加載程序集
-
-
//獲得對(duì)象類型
-
Type type = assembly.GetType("StudyConsole.Student",true,true);
-
-
//獲取所有公有的屬性,不區(qū)分大小寫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("屬性類型:{0},屬性值:{1}", field.PropertyType, field.Name);
-
}
-
-
}
-
}
-
-
class Student
-
{
-
public string Name { get; set; }
-
public int Age { get; set; }
-
public string *** { get; set; }
-
}
-
}
|
|