objective-c 多态 ——动态类型 id 的使用(与 C# 的比较说明)
2011-02-11 15:08
706 查看
在C#中,我们用接口来实现多态。比如接口IOb,定义了1个方法F; 有两个类A,B都实现了IOb接口。
IOb item = new A();
item.F();//执行的是A.F();
item = new B();
item.F();//执行的B.F();
在objective-c中,interface 的含义和C#有了很大的不同,不能这样使用。
那么如何实现类似的效果呢。那就是特殊类型id,看如下代码段,注释:Fraction 和 Complex都包含print 方法。
#import “Fraction.h”
#import “Complex.h”
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
id dataValue;//定义了一个id 类型变量
Fraction *f1 = [[Fraction alloc] init];
Complex *c1 = [[Complex alloc] init];
[f1 setTo: 2 over: 5];
[c1 setReal: 10.0 andImaginary: 2.5];
// first dataValue gets a fraction
dataValue = f1;
[dataValue print]; //调用Fraction的 print方法
// now dataValue gets a complex number
dataValue = c1;
[dataValue print]; //调用Complex的 print方法[c1 release];
[f1 release];
[pool drain];
return 0;
}
IOb item = new A();
item.F();//执行的是A.F();
item = new B();
item.F();//执行的B.F();
在objective-c中,interface 的含义和C#有了很大的不同,不能这样使用。
那么如何实现类似的效果呢。那就是特殊类型id,看如下代码段,注释:Fraction 和 Complex都包含print 方法。
#import “Fraction.h”
#import “Complex.h”
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
id dataValue;//定义了一个id 类型变量
Fraction *f1 = [[Fraction alloc] init];
Complex *c1 = [[Complex alloc] init];
[f1 setTo: 2 over: 5];
[c1 setReal: 10.0 andImaginary: 2.5];
// first dataValue gets a fraction
dataValue = f1;
[dataValue print]; //调用Fraction的 print方法
// now dataValue gets a complex number
dataValue = c1;
[dataValue print]; //调用Complex的 print方法[c1 release];
[f1 release];
[pool drain];
return 0;
}
相关文章推荐
- objective-c 多态 ——动态类型 id 的使用(与 C# 的比较说明)
- objective-c 多态 — 动态类型 id 的使用
- Objective-C多态:动态类型识别+动态绑定+动态加载
- Programming in Objective C学习笔记03——多态、动态绑定和动态类型
- ASP.NET MVC 2.0 in Vs2010 :使用C# 4.0中使用动态类型来传递ViewData
- Objective-C的动态绑定和id类型
- C# 使用DateTimePicker与数据库中类型为datetime的数据作比较的一些注意事项
- [学习笔记—Objective-C]《Objective-C 程序设计 第6版》第九章 多态,动态类型和动态绑定
- Objective-C多态:动态类型识别+动态绑定+动态加载
- 【点滴积累】在C#中使用反射动态调用类型成员
- Objective-C多态:动态类型识别+动态绑定+动态加载
- Objective-C语法之动态类型(isKindOfClass, isMemberOfClass,id)等
- objective-c(七)-id数据类型及多态
- Objective-C语法之动态类型(isKindOfClass, isMemberOfClass,id)等
- Objective-C语法之动态类型(isKindOfClass, isMemberOfClass,id)等
- Objective-c 特性之多态、动态类型和动态绑定
- Objective-C语法之动态类型(isKindOfClass, isMemberOfClass,id)等
- Objective-C语法之动态类型(isKindOfClass, isMemberOfClass,id)等
- 8、Objective-C语法之动态类型(isKindOfClass, isMemberOfClass,id)等
- ASP.NET MVC 2.0 in Vs2010 :使用C# 4.0中使用动态类型来传递ViewData