• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

objective-C中如何判断一个类中有没有定义某个方法

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
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;
}


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
iOS--EffectiveObjective-C阅读笔记(7)发布时间:2022-07-12
下一篇:
2012年12月编程语言排行榜:Objective-C风暴来袭(1)发布时间:2022-07-12
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap