C#中可以通過反射分析中繼資料來解決這個問題,範例程式碼如下:
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!"); } }}
在obj-C中,則是通過選取器selector來判斷的
Sampe.h
#import <Foundation/Foundation.h>@interface Sample : NSObject {}-(void) print:(NSString*) msg;@end
Sample.m
#import "Sample.h"@implementation Sample-(void) print:(NSString*) msg{NSLog(@"%@",msg);}@end
main函數:
#import <Foundation/Foundation.h>#import "Sample.h"int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];Sample *s = [Sample new];if ([s respondsToSelector:@selector(print:)]) //這一行就是判斷執行個體s中有沒有方法print{[s print:@"Hello World"];}else{NSLog(@"%@",@"Sample類中沒有定義方法print");}[s release]; [pool drain]; return 0;}