標籤:blog ar io color sp for on 資料 div
C#中可以通過反射分析中繼資料來解決這個問題,範例程式碼如下:
| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
using System;using System.Reflection; namespace Hello{ class Program { static void Main(string[] args) { if (IsMethodDefined(typeof(Utils), "HelloWorld")) { Console.WriteLine("Utils類中有方法HelloWorld"); } else { Console.WriteLine("Utils類中沒有方法HelloWorld"); } Console.ReadKey(); } /// <summary> /// 判斷一個類中有無"指定名稱"的方法 /// </summary> /// <param name="type"></param> /// <param name="methodName"></param> /// <returns></returns> static bool IsMethodDefined(Type type,string methodName) { bool result = false; foreach (MemberInfo m in type.GetMembers()) { if (m.Name == methodName) { result = true; break; } } return result; } } public static class Utils { public static void HelloWorld() { Console.WriteLine("Hello World!"); } }} |
C#判斷一個類中有無"指定名稱"的方法