前段時間在一個項目中,在一個地方要將函數所在類中的方法都調用一遍,但是否調用要通過配置文件中的內容決定。所以為了減少代碼量,在網上查了相關信息,終於成功的將其應用到了項目中,我在這裡將我做的一個簡單例子提供給大家,便於大家方便下載和理解。 主要用到了反射的一個特性,主要代碼如下: 基本步驟就是: 1 ...
前段時間在一個項目中,在一個地方要將函數所在類中的方法都調用一遍,但是否調用要通過配置文件中的內容決定。所以為了減少代碼量,在網上查了相關信息,終於成功的將其應用到了項目中,我在這裡將我做的一個簡單例子提供給大家,便於大家方便下載和理解。
主要用到了反射的一個特性,主要代碼如下:
object[] _params = new object[kvp.Value.Length]; for (int i = 0; i <= _params.Length - 1; i++) { _params[i] = kvp.Value[i]; } Type t = typeof(ListOfWay); MethodInfo mi = t.GetMethod(kvp.Key.ToString()); object objinstance = Activator.CreateInstance(t); int result = (int)mi.Invoke(objinstance, _params);
基本步驟就是:
1、將要調用的方法的參數全部依次放入一個object數組中;
2、用反射一個特性,獲得方法所在類的類型;
3、根據對象和方法參數去調用這個方法。
詳細代碼:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Reflection; using TestWay; namespace 載入xml及調用字元串名的函數 { class Program { static void Main(string[] args) { Dictionary<string, string[]> dict = new Dictionary<string, string[]>(); string path = @"InputParam.xml"; ReadXml(path, dict); foreach (KeyValuePair<string, string[]> kvp in dict) { #region 根據字元串去調用與字元串相同名稱的方法 object[] _params = new object[kvp.Value.Length]; //根據鍵值對中值的多少聲明一個同樣大小的字元串數組 for (int i = 0; i <= _params.Length - 1; i++) { _params[i] = kvp.Value[i]; //將鍵值對中的值寫入數組中 } Type t = typeof(ListOfWay); //獲得方法所在的類的類型 MethodInfo mi = t.GetMethod(kvp.Key.ToString()); //根據字元串名稱獲得對應的方法 object objinstance = Activator.CreateInstance(t); //創建一個方法所在的類的一個對象 int result = (int)mi.Invoke(objinstance, _params); //根據對象和方法參數去執行方法 #endregion Console.WriteLine(result); } Console.ReadLine(); } #region Way2 /// <summary> /// 讀取XML文檔 /// </summary> /// <param name="path">xml路徑(含名稱)</param> /// <param name="dict">xml中參數字典</param> public static void ReadXml(string path, Dictionary<string, string[]> dict) { XmlDocument xml = new XmlDocument(); xml.Load(path); XmlElement xmlRoot = xml.DocumentElement; //根節點 XmlNodeList xmllist = xmlRoot.ChildNodes; //根節點下所有子節點(一般是二級節點) foreach (XmlNode item in xmllist) { XmlNodeList inxmllist = item.ChildNodes; //每個子節點下的所有子節點(一般是三級節點,也基本是最內層節點) string[] param = new string[inxmllist.Count]; for (int i = 0; i <= inxmllist.Count - 1; i++) { param[i] = inxmllist[i].InnerText; //將每個子節點的值放入數組 } dict.Add(item.Name, param); } } #endregion } }View Code
用於測試的方法所在的類的代碼:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestWay { public class ListOfWay { public int Add(string a, string b) { return Convert.ToInt32(a) + Convert.ToInt32(b); } public int Sub(string a, string b) { return Convert.ToInt32(a) - Convert.ToInt32(b); } public int Mul(string a, string b) { return Convert.ToInt32(a) * Convert.ToInt32(b); } public int Div(string a, string b) { return Convert.ToInt32(a) / Convert.ToInt32(b); } } }View Code