Odd shared inheritance pattern

During some research, I came across a generic inheritance pattern that I had not seen before.

http://thwadi.blogspot.ca/2013/07/using-protobuff-net-with-inheritance.html

public abstract class BaseClass<TClass> where TClass : BaseClass<TClass>
{
    //...
}
public class DerivedClass : BaseClass<DerivedClass>
{
    //...
}

Using:

static void Main(string[] args)
{
    DerivedClass derivedReference = new DerivedClass();

    //this looks odd...
    BaseClass<DerivedClass> baseReference = derivedReference;

    //this doesn't work
    //BaseClass baseClass = derivedReference;

}

I was surprised that it even worked, I had to test it myself. I still don't understand why you want to do this.

The only thing I could think of was to prevent the storage of various derived classes in a collection together as their base class. This may be the reason, I think I'm just curious about the application.

+3
source share
2 answers

, , .

, Clone, , , .

public abstract class BaseClass<TClass> where TClass : BaseClass<TClass>, new()
{
    public int Foo {get;set;}

    public virtual TClass Clone()
    {
        var clone = new TClass();
        clone.Foo = this.Foo;
        return clone;
    }
}
public class DerivedClass : BaseClass<DerivedClass>
{
    public int Bar {get;set;}

    public override DerivedClass Clone()
    {
        var clone = base.Clone();
        clone.Bar = this.Bar;
        return clone;
    }
}

:

static void Main(string[] args)
{
    DerivedClass derivedReference = new DerivedClass();

    DerivedClass clone = derivedReference.Clone();    
}
+4

, , :

var d = new DerivedClass();
d.SetPropertyA("some value").SetPropertyB(1);

SetPropertyA , SetPropertyB .

, , SetPropertyA, DerivedClass, SetPropertyB:

public abstract class BaseClass<TClass> where TClass : BaseClass<TClass>
{
    public string A {get ; set; }
    public TClass SetPropertyA(string value)
    {
        this.A=value;
        return this as TClass;
    }
}

public class DerivedClass : BaseClass<DerivedClass>
{
    public int B {get ; set; }
    public DerivedClass SetPropertyB(int value)
    {
        this.B=value;
        return this;
    }
}

, , SetPropertyA, , .

+3

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


All Articles