標籤:style blog class code java tar
反射 Reflection 中存取方法
建立一個ClassLibrary類庫:
public class Student { public string Name { get; set; } public string School { get; set; } public int Sum(int a, int b) { return a + b; } public string GetName() { return "this is book" ; } }
/// <summary> /// 反射 /// </summary> class Program { static void Main(string[] args) { Assembly assembly = Assembly.Load("ClassLibrary");//調用 程式集 類的方法 //建立該對象的執行個體,object類型,參數(名稱空間+類) object instances = assembly.CreateInstance("ClassLibrary.Student"); //無參數 返回 object value = type.GetMethod("GetName").Invoke(instances, null); //返回this is book //有參 object[] params_obj = new object[2]; params_obj[0] = 12; params_obj[1] = 23; object value1 = type.GetMethod("Sum").Invoke(instances, params_obj);
//返回a b和 }
還可以通過 FindInterfaces 方法返回 介面資訊
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//擷取程式集介面 Stu 繼承的所有介面 Type t = typeof(Stu); Type[] interfaces = t.FindInterfaces(TypeFilter, assembly); //顯示每個介面資訊 foreach (Type i in interfaces) { //擷取映射介面方法的類型的方法 InterfaceMapping mapping = t.GetInterfaceMap(i); for (int j = 0; j < mapping.InterfaceMethods.Length; j++) { Console.WriteLine(" {0} 實現的 {1}", mapping.InterfaceMethods[j], mapping.TargetMethods[j]); } } |