3

This is a problem which seems super basic but I still can't find a way to clear it. When I have a simple inheritance like B and C inheriting from A

   A
   |
|-----|
B     C

Let's say these are interface like:

public interface A
{
    List<A> Children { get; }
}

My issue: When I got through B.Children I have to cast it to B every time I want to use its specifics. Is there a way to have a list of children without having to declare the children in the leaves of the inheritance tree?

Precision: A child is always of the same type as its parent (or sub-type). And the tree can go deeper. As an example, think about a UI system with objects, containers, controls, labels where a class has as children only things of the same type or sub-types of itself.


Here is my code. I have the top level as

public interface ITerm
{
    String text { get; }
}

Then, as offered by @Damien_The_Unbeliever

public interface ITerm<T> : ITerm where T : ITerm
{
    List<T> Children { get; }
}

public interface ITermControl : ITerm<ITermControl> { ... }

public class TermControl : ITermControl { ... }

I am starting to think it is useless to have access to a List<ITerm> ITerm.Children as well as List<ITermControl> ITermControl.Children. That's what I was trying to explain.

Thanks

4

1 回答 1

4

您可以尝试这样做:

public interface A<T> where T: A<T> {
    List<T> Children {get;}
}

Eric Lippert 在他的文章Curiouser 和 Curiouser中描述了这一点:

这是 C++ 中所谓的奇怪重复模板模式的 C# 变体,我将把它留给我的高手来解释它在该语言中的用途。本质上,C# 中的模式是尝试强制使用 CRTP。

并指出它并没有真正在整个过程中强制执行正确的类型——所以充其量,它是一种文档形式,而不是防止坏事发生的东西。

于 2013-07-01T06:25:39.427 回答