在.NET中有一个非常带劲的特性,那就是扩展方法. 扩展方法使你能够向现有类型“添加”方法(包括你自定义的类型和对象噢),而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但是可以像扩展类型上的实例方法一样进行调用。

  先看看.NET中扩展方法的定义和使用

    public static class test
    {
        public static bool In(this object o, IEnumerable c)
        {
            foreach (object obj in c)
                if (obj.Equals(o))
                    return true;
            return false;
        }
    }
    string[] list = new string[] { "abc" , "123", "C#"};
    Console.WriteLine("Object C".In(list));

  在.NET中Object 类并没有In方法的定义,但是的确用"Object C"方法调用了In方法。

 

  Object C中的分类(category) 又称类别在不修改原有的类的基础上增加新的方法,和.NET一样不能添加新的实例变量。

 

  新增一个Person的Object C对象,在Person.h文件中定义相应的书属性name和age,并且定义一个方法:

  -(void) addName:(NSString*) name1 andWithAge:(int) age1;

#import <Foundation/Foundation.h>

@interface Person : NSObject{
    NSString *name;
    int age;
}

@property (retain) NSString *name;
@property (nonatomic)int age;

-(void) addName:(NSString*) name1 andWithAge:(int) age1;

@end
Person.h

相关文章:

  • 2021-08-10
  • 2022-12-23
  • 2021-10-19
  • 2021-07-26
  • 2021-10-01
  • 2021-12-29
  • 2021-09-01
  • 2021-11-13
猜你喜欢
  • 2021-10-01
  • 2022-12-23
  • 2022-12-23
  • 2021-05-18
  • 2022-03-04
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案