In C #, the closest thing to C ++ style mixes is adding mixins as the fields of a class, and a bunch of transfer methods are added to the class:
public class MyClass { private readonly Mixin1 mixin1 = new Mixin1(); private readonly Mixin2 mixin2 = new Mixin2(); public int Property1 { get { return this.mixin1.Property1; } set { this.mixin1.Property1 = value; } } public void Do1() { this.mixin2.Do2(); } }
This is usually enough if you want to import the functionality and state of mixes. Of course, mixin can be implemented as you like, complete with (private) fields, properties, methods, etc.
If your class also needs to express an is-a relationship with mixins, you need to do the following:
interface IMixin1 { int Property1 { get; set; } } interface IMixin2 { void Do2(); } class MyClass : IMixin1, IMixin2 {
(This is also the standard way how multiple inheritance is emulated in C #.)
Of course, mixin interfaces as well as mixin classes can be generics, for example. with the parameter of the most derived class or any other.
source share