且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中实现类之间的共享行为(没有多重继承)

更新时间:2022-01-23 02:03:34

不可变数据值类。 如果您的各种候选子类中的任何属性表示某种有意义的数据值,请为所需的行为创建一个不可变类。每个不同的候选子类都可以使用数据类型,但你的代码仍然封装在数据类中。

Immutable data value classes. If any properties in your various Candidate subclasses represent some kind of meaningful data value, create an immutable class for it, with the behaviors you need. Each of your distinct Candidate subclasses can then use the data type, but your code is still encapsulated in the data classes.

扩展方法可以重载任何类。

我将避免装饰器模式,并坚持编译/反映功能。

I'd avoid the decorator pattern and stick with compiled/reflectable functionality.

构图。立即在单独的类中开发独特的行为,并围绕它们构建您的Candidate类,而不是在Candidate类中编写独特的行为,并尝试将其功能用于

Composition. Develop the unique behaviors in separate classes right away, and build your Candidate classes around them, rather than writing unique behaviors in your Candidate classes and trying to pull out their functionality for use in related classes later.

根据您如何使用类,您还可以将显式和隐式转换运算符实现为相关类型,因此不需要重新实现接口(你想避免的),你实际上可以把你的对象放入你需要的类型/实现中。

Depending on how you use the classes, you could also implement and make use of explicit and implicit conversion operators to a related type, so instead of reimplementing interfaces (which you wanted to avoid), you could actually cast your object into the type/implementation you need for whatever purpose.

另一件事我只是与最后一段相关的是,有一个租赁系统,您的类产生和适当类型的对象,允许其被操纵,然后消费以吸收更新的信息。

Another thing I just thought of, related to that last paragraph, is to have a leasing system, where your class spawns and object of the appropriate type, allows it to be manipulated, then consumes it later to assimilate the updated information.