【问题标题】:C# unusual inheritance syntax w/ generics带有泛型的 C# 不寻常的继承语法
【发布时间】:2011-06-05 15:42:42
【问题描述】:

我在 NHibernate 类定义中遇到了这个问题:

public class SQLiteConfiguration : PersistenceConfiguration<SQLiteConfiguration>

所以这个类继承自一个基类,该基类由...派生类参数化?我的头刚刚爆炸。

有人能解释一下这是什么意思以及这种模式有什么用处吗?

(顺便说一句,这不是一个特定于 NHibernate 的问题。)

【问题讨论】:

  • Eric:我在我的 cmets 中向 Lambert 引用了这个 SO 问题。
  • 我很久以前读过这个帖子,但现在才遇到这个特定的场景。我通过搜索“我的头刚刚爆炸”再次找到了该主题。哈哈。好东西是你写的,否则我可能再也找不到了。 :-)
  • “Curiously Recurring Template Pattern”是个很无聊的名字。我在此将这种模式重新命名为“颅骨破裂模板模式”。

标签: c# generics inheritance syntax design-patterns


【解决方案1】:

【讨论】:

【解决方案2】:

我在开发双链树时使用了相同的模式。每个节点有 1 个父节点和 0 个子节点

class Tree<T> where T : Tree<T>
{
    T parent;
    List<T> children;
    T Parent { get; set; }
    protected Tree(T parent) 
    {
        this.parent = parent; 
        parent.children.Add(this);
    }
    // lots more code handling tree list stuff
}

实现

class Coordinate : Tree<Coordinate>
{
    Coordinate(Coordinate parent) : this(parent) { }
    static readonly Coordinate Root = new Coordinate(null);
    // lots more code handling coordinate systems
}

用法

Coordinate A = Coordinate.Root;
Coordinate B = new Coordinate(A);

B.Parent // returns a Coordinate type instead of a Node<>.

所以从Tree&lt;&gt; 继承的任何东西都将包含适当类型的父对象和子对象的属性。这个技巧对我来说是纯粹的魔法

【讨论】:

  • 谢谢你,jalexiou,非常具体的回复!我不得不承认,我需要一段时间才能理解这一点。
  • @anon - 试试看!启动旧的 C# 开发并编写类似这样的代码。
  • @anon - 当然,它缺少构造函数、属性访问器等等。它只是骨架代码。
猜你喜欢
  • 1970-01-01
  • 2018-02-28
  • 2020-05-17
  • 2011-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多