📜 ⬆️ ⬇️

C # - “Multiple Inheritance” in the class property (or function parameter)

The topic was born from the question Multiple Inheritance in C # for properties (or function parameters) . After reading the shedal article on the advice, I came up with a method like in C # to specify several interfaces as a type.

In C #, you can make a class implement multiple interfaces. And if you want multiple interfaces to implement the property? Do not create every time for this new type?


')
So, we will group interfaces using a tuple that appeared in dotNET 4 (Tuple <> class). In dotNET version 3, a tuple can be made by yourself - it’s easy.

interface IClickableButton { event Action Click; } interface IColorButton { Color Color { get; set; } } interface IButtonWithText { string Text { get; set; } } interface IMyForm1 { Tuple<IClickableButton, IColorButton> Button { get; } } interface IMyForm2 { Tuple<IClickableButton, IButtonWithText> Button { get; } } interface IMyForm3 { Tuple<IClickableButton, IColorButton, IButtonWithText> Button { get; } } public class Button : IClickableButton, IColorButton, IButtonWithText { public event Action Click; public Color Color { get; set; } public string Text { get; set; } } class MyForm1 : IMyForm1 { private readonly Button _button = new Button(); public Tuple<IClickableButton, IColorButton> Button { get { return new Tuple<IClickableButton, IColorButton>(_button, _button); } } } class MyForm2 : IMyForm2 { private readonly Button _button = new Button(); public Tuple<IClickableButton, IButtonWithText> Button { get { return new Tuple<IClickableButton, IButtonWithText>(_button, _button); } } } class MyForm3 : IMyForm3 { private readonly Button _button = new Button(); public Tuple<IClickableButton, IColorButton, IButtonWithText> Button { get { return new Tuple<IClickableButton, IColorButton, IButtonWithText>(_button, _button, _button); } } } class UsageExample { void Example1(IMyForm1 form) { form.Button.Item1.Click += () => { }; form.Button.Item2.Color = Colors.Red; } void Example2(IMyForm2 form) { form.Button.Item1.Click += () => { }; form.Button.Item2.Text = "Hello, World!"; } void Example2(IMyForm3 form) { form.Button.Item1.Click += () => { }; form.Button.Item2.Color = Colors.Red; form.Button.Item3.Text = "Hello, World!"; } } 


In words: there are three interfaces that describe the properties of a button: the “Clickable Button”, the “Color Button” and the “Button Text”. It is necessary to abstract so that only the minimum necessary set of properties is transferred to the methods Example1, Example2 and Example3 . At the same time, strict typification should be maintained.

Using the Tuple <> class, we group the necessary interfaces - that's it! Now properties can be accessed via Item1, Item2, Item3 , etc. With the help of a tuple, at least a dozen interfaces can be combined.

If someone has a more beautiful solution - let's try!

Source: https://habr.com/ru/post/123229/


All Articles