在运行时创建哪种派生类型的类
我试图理解一些类似的帖子,但不太明白它们的目的,并认为我会解释我自己的......
我有一个类 - 完全用带有属性和方法的代码定义。许多方法都是虚拟的,可以被进一步的派生类覆盖。因此,我有类似以下内容,
Class_Main
-- Class_A : Class_Main
-- Class_B : Class_Main
-- Class_C : Class_Main
-- Class_D : Class_Main
然后我需要定义一个可以从 AD 动态派生的类...例如:
Class_X : Class_A (or Class_B or Class_C or Class_D )
因为我在 Class_X 中有其他属性和方法。由于 C# 不能从两个实际的类派生,但可以使用接口,但接口中不能有代码,只能有抽象签名,所以我该如何进行这样的实现。
谢谢
I've tried to understand some of the posts of similar, but don't quite understand their purposes and thought I'd explain my own...
I have a class -- fully defined with code with properties, and methods. Many methods are virtual to be overriden by further derived class. So, I have something like the following
Class_Main
-- Class_A : Class_Main
-- Class_B : Class_Main
-- Class_C : Class_Main
-- Class_D : Class_Main
I then need to define one more class that can be dynamically derived from A-D... such as:
Class_X : Class_A (or Class_B or Class_C or Class_D )
as I have additional properties and methods within the Class_X. Since C# can't derive from two actual classes, but can use interfaces, but you can't have code in an interface, just abstract signatures, how might I go about doing such implementation.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您所描述的内容听起来有点像鸭子打字。这在 C# 中不可用,因为它是一种静态类型语言。也许当 C# 4 出现时,
dynamic< /code>
会给你你正在寻找的东西。
如果
Class_X
需要用这些类的功能“填充”,通常会在实例化时将其传递到类中:此时,您的
Class_X
> 实例可以访问Class_Main
属性&所有派生类的方法。这不会使Class_X
成为聚合,只是使您能够使用Class_X
中任何Class_Main
的运行时行为(通过_impl
对象)。What you are describing sounds a bit like duck typing. This isn't available in C#, as it is a statically-typed language. Perhaps when C# 4 comes around,
dynamic
will give you what you are looking for.If
Class_X
needs to be "filled in" with functionality from those classes, it would be common to pass that into the class at the time of instantiation:At this point, your
Class_X
instances have access to theClass_Main
properties & methods for all derived classes. This doesn't makeClass_X
an aggregate, just enables you to use the runtime behavior of anyClass_Main
from withinClass_X
(through the_impl
object).从一个类扩展并将另一个类包含在 X 类中,并且只需使用适配器方法直接映射到其中的类。
所以,现在完全是 C#,只是原型设计:
所以,ClassX 现在有一个从 ClassA 继承(从外观上看)的函数,并且包含 ClassB 的所有方法。
Extend from one class and include the other class within Class X, and just have adapter methods to map directly to the class inside.
So, now exactly C#, just prototyping:
So, ClassX now has one function inherited (by appearance) from ClassA, and contains all the methods of ClassB.