有没有办法在目标C上动态声明类?

时间:2023-01-15 15:08:23

I just think about this case, I want to declare a class C which extends from other classes dynamically. Suppose that I have class A and class B. Now, I want the class C extends A or B base on a specified condition such as:

我只想到这种情况,我想声明一个C类,它动态地从其他类扩展。假设我有A类和B类。现在,我希望C类基于指定的条件扩展A或B,例如:

#ifdef USE_CLASS_A
class C: A
#else 
Class C: B
#endif

I don't have more experiences with objective C and ios. So please tell me if I can do this.

我对目标C和ios没有更多经验。所以请告诉我是否可以这样做。

Thanks a bunch :)

谢谢一堆:)

UPDATE: I just need dynamic at compile time, not runtime. I mean, during compiling time, the class C will extend A or B. This extending will be go forever, don't change at runtime.

更新:我只需要在编译时动态,而不是运行时。我的意思是,在编译时,C类将扩展A或B.这种扩展将永远存在,不要在运行时更改。

1 个解决方案

#1


1  

Based on your update the answer is yes - using #if/#ifdef you can determine at compile time whether class C extends class A or class B in exactly the way you have suggested.

基于您的更新,答案是肯定的 - 使用#if / #ifdef您可以在编译时确定C类是否完全按照您的建议扩展A类或B类。

Of course classes A & B better provide same set of common methods and your code only call those methods, or else you will need further conditional code (compile or runtime) at the points you use class C.

当然,类A和B更好地提供相同的公共方法集,并且您的代码只调用这些方法,否则您将需要在使用类C的点处进一步的条件代码(编译或运行时)。

#1


1  

Based on your update the answer is yes - using #if/#ifdef you can determine at compile time whether class C extends class A or class B in exactly the way you have suggested.

基于您的更新,答案是肯定的 - 使用#if / #ifdef您可以在编译时确定C类是否完全按照您的建议扩展A类或B类。

Of course classes A & B better provide same set of common methods and your code only call those methods, or else you will need further conditional code (compile or runtime) at the points you use class C.

当然,类A和B更好地提供相同的公共方法集,并且您的代码只调用这些方法,否则您将需要在使用类C的点处进一步的条件代码(编译或运行时)。