奇怪的通用继承模式 [英] Odd Generic Inheritance pattern

查看:37
本文介绍了奇怪的通用继承模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在进行一些研究时,我遇到了使用以前从未见过的泛型的继承模式.

During some research, I ran into an inheritance pattern using generics I have 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>
{
    //...
}

用法:

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 this even worked, I had to test it myself. I still can't understand why you would want to do this.

我唯一能想到的就是防止将不同的派生类作为基类一起存储在集合中.这可能是原因,我想我对应用程序很好奇.

The only thing I could come up with, is preventing different derived classes from being stored in a collection together as their base class. This may be the reason, I guess I'm just curious to the application.

推荐答案

它称为好奇地重复出现的模板模式它通常用于允许类中的方法使用派生类的类型作为传入或返回的参数.

It is called the Curiously recurring template pattern it is often used to allow methods in the class to use the type of the derived class as a passed in or returned parameter.

例如,这是通过Clone方法实现的,因此,当沿着链向下移动时,只有每一层都需要将其自己的属性添加到该方法中.

For example, this is Clone method implemented so that only each layer needs to add it's own properties to the method as it goes down the chain.

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();    
}

这篇关于奇怪的通用继承模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆