N
N
ndbn2016-06-30 09:30:29
OOP
ndbn, 2016-06-30 09:30:29

How to make inheritance from multiple classes in C#?

Hello.
All classes must have a base class MyBaseClass so that they have a BaseObject field of type T and store their field values ​​there.
But when inheriting, as in the case of FakeClass2, it inherits from FakeClass1, and its BaseObject must be of type RealClassForFakeClass2.
Is it possible to implement this?
As far as I understand, it is possible to inherit from FakeClass1, and override BaseObject in the class itself, but I would like it to be possible to somehow implement such an approach without overlapping in the class itself, either through MyBaseClass or something else.

public class MyBaseClass<T>
    where T : class, new()
{
    protected T BaseObject = default(T);
    public T getBaseObject()
    {
        return this.BaseObject;
    }
}

public class FakeClass1 : MyBaseClass<RealClassForFakeClass1>
{
    public string Field1
    {
        set
        {
            this.BaseObject.Field1 = value;
        }
    }

    public string Field2
    {
        set
        {
            this.BaseObject.Field2 = value;
        }
    }
}
    
public class FakeClass2 : FakeClass1, MyBaseClass<RealClassForFakeClass2> ////error
{
    public FakeClassN Field1
    {
        set
        {
           this.BaseObject.Field1 = value.getBaseObject(); 
        }
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Neonoviiwolf, 2016-06-30
@Neonoviiwolf

Not possible, use interfaces and composition

D
Dmitry Kovalsky, 2016-06-30
@dmitryKovalskiy

In any C# textbook, the first thing they would say in the chapter on inheritance is that this is impossible. There is no solution for a spherical problem in vacuum. For more specific - you can find any architectural solutions. If you don't want to inherit the implementation of these classes, do it via interfaces.

#
#algooptimize #bottize, 2016-06-30
@user004

No way, just use a proxy, you can generate it on t4, if you write a lot and more than once.
I did not study the code from the mobile phone, the answer is in theory. In fact, there may be a problem with the logic if inheritance from several classes is required.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question