反射允許我們在編譯期或運行時獲取程序集的元數據,通過反射可以做到:
● 創建類型的實例
● 觸發方法
● 獲取屬性、字段信息
● 延遲綁定
......
如果在編譯期使用反射,可通過如下2種方式獲取程序集Type類型:
1、Type類的靜態方法
Type type = Type.GetType("somenamespace.someclass");
2、通過typeof
Type type = typeof(someclass);
如果在運行時使用反射,通過運行時的Assembly實例方法獲取Type類型:
Type type = asm.GetType("somenamespace.someclass");
獲取反射信息
有這樣的一個類:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public float Score { get; set; }
public Student()
{
this.Id = -1;
this.Name = string.Empty;
this.Score = 0;
}
public Student(int id, string name, float score)
{
this.Id = id;
this.Name = name;
this.Score = score;
}
public string DisplayName(string name)
{
return string.Format("學生姓名:{0}", name);
}
public void ShowScore()
{
Console.WriteLine("學生分數是:" + this.Score);
}
}
通過如下獲取反射信息:
static void Main(string[] args)
{
Type type = Type.GetType("ConsoleApplication1.Student");
//Type type = typeof (Student);
Console.WriteLine(type.FullName);
Console.WriteLine(type.Namespace);
Console.WriteLine(type.Name);
//獲取屬性
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
Console.WriteLine(prop.Name);
}
//獲取方法
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
Console.WriteLine(method.ReturnType.Name);
Console.WriteLine(method.Name);
}
Console.ReadKey();
}
延遲綁定
Student stu = new Student(); stu.Name = "somename";
而"延遲綁定",為對象實例賦值或調用其方法是發生在運行時,需要獲取在運行時的程序集、Type類型、方法、屬性等。
//獲取運行時的程序集
Assembly asm = Assembly.GetExecutingAssembly();
//獲取運行時的Type類型
Type type = asm.GetType("ConsoleApplication1.Student");
//獲取運行時的對象實例
object stu = Activator.CreateInstance(type);
//獲取運行時指定方法
MethodInfo method = type.GetMethod("DisplayName");
object[] parameters = new object[1];
parameters[0] = "Darren";
//觸發運行時的方法
string result = (string)method.Invoke(stu, parameters);
Console.WriteLine(result);
Console.ReadKey();