C#中可以通過反射分析元數據來解決這個問題,示例代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 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!" ); ???????? } ???? } } |