c#中多个奇怪的重复模板模式(CRTP)?

multiple curiously recurring template pattern (CRTP) in c#?

我试图将CRTP接口实现到我的代码中,但是约束使我陷入困境。如果我有这样的代码结构,如何实现约束?这合法吗?谢谢您。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
interface IInterface<T>
    where T: IInterface<T>
{
    //bla bla bla
    T Member { get; set; }
}
interface ITest1<iTest2, iTest1> : IInterface<iTest2>
{
    //bla bla bla
}
interface ITest2<iTest1, iTest3> : IInterface<iTest1>
{
    iTest3 RefMember { get; set; }
    //bla bla bla
}
interface ITest3<iTest2>
{
    List<iTest2> manyTest { get; set; }
    //bla bla bla
}
class Test1 : ITest1<Test2, Test1>
{
    //bla bla bla
}
class Test2 : ITest2<Test1, Test3>
{
    //bla bla bla
}
class Test3 : ITest3<Test2>
{
    //bla bla bla    
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 public abstract class MyBase
{
    /// <summary>
    /// The my test method. divyang
    /// </summary>
    public virtual void MyVirtualMethodWhichIsOverridedInChild()
    {
        Console.Write("Method1 Call from MyBase");
    }

    /// <summary>
    /// The my another test method.
    /// </summary>
    public abstract void MyAnotherTestMethod();

    /// <summary>
    /// The my best method.
    /// </summary>
    public virtual void MyVirualMethodButNotOverridedInChild()
    {
        Console.Write("Method2 Call from MyBase");
    }
}

现在让基类

1
2
3
4
public abstract class CrtpBaseWrapper<T> : MyBase
    where T : CrtpBaseWrapper<T>
{
}

然后你可以让你的类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class CrtpChild : CrtpBaseWrapper<CrtpChild>
{
    /// <summary>
    /// The my test method. divyang
    /// </summary>
    public override void MyVirtualMethodWhichIsOverridedInChild()
    {
        Console.Write("Method1 Call from CrtpChild");
    }

    /// <summary>
    /// The my another test method.
    /// </summary>
    public override void MyAnotherTestMethod()
    {
        Console.Write("MyAnotherTestMethod Call from CrtpChild");
    }
}