簡體   English   中英

如何使用反射調用方法

[英]How are methods invoked using Reflection

我想知道如何在c#中使用Reflection調用這些方法。

這是我從書中挑選的代碼

 using System; using System.Reflection; class MyClass { int x; int y; public MyClass(int i, int j) { x = i; y = j; } public int Sum() { return x+y; } public bool IsBetween(int i) { if((x < i) && (i < y)) return true; else return false; } public void Set(int a, int b) { Console.Write("Inside Set(int, int). "); x = a; y = b; Show(); } // Overload set. public void Set(double a, double b) { Console.Write("Inside Set(double, double). "); x = (int) a; y = (int) b; Show(); } public void Show() { Console.WriteLine("Values are x: {0}, y: {1}", x, y); } public void Show1() { Console.WriteLine("Hello"); } } class InvokeMethDemo { static void Main() { Type t = typeof(MyClass); MyClass reflectOb = new MyClass(10, 20); int val; Console.WriteLine("Invoking methods in " + t.Name); Console.WriteLine(); MethodInfo[] mi = t.GetMethods(); // Invoke each method. foreach(MethodInfo m in mi) { // Get the parameters. ParameterInfo[] pi = m.GetParameters(); if(m.Name.Equals("Set", StringComparison.Ordinal) && pi[0].ParameterType == typeof(int)) { object[] args = new object[2]; args[0] = 9; args[1] = 18; m.Invoke(reflectOb, args); } else if(m.Name.Equals("Set", StringComparison.Ordinal) && pi[0].ParameterType == typeof(double)) { object[] args = new object[2]; args[0] = 1.12; args[1] = 23.4; m.Invoke(reflectOb, args); } else if(m.Name.Equals("Sum", StringComparison.Ordinal)) { val = (int) m.Invoke(reflectOb, null); Console.WriteLine("sum is " + val); } else if(m.Name.Equals("IsBetween", StringComparison.Ordinal)) { object[] args = new object[1]; args[0] = 14; if((bool) m.Invoke(reflectOb, args)) Console.WriteLine("14 is between x and y"); } else if(m.Name.Equals("Show", StringComparison.Ordinal)) { m.Invoke(reflectOb, null); } else if(m.Name.Equals("Show1", StringComparison.Ordinal)) { m.Invoke(reflectOb, null); } } } } 
  1. 是否根據傳遞的參數的數量和類型來調用方法?

編譯器不會顯示錯誤,因為**相同的語句用於調用方法show和

show1 **?

要么

  1. 方法是根據一些參考值m (MethodInfo m) 和參數數量來調用的。

您可以使用MethodBase類調用方法。

使用指定的參數調用當前實例表示的方法或構造函數。 請參考此鏈接反射中的方法調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM