0

我试图为我的代码实现 CRTP 接口,但约束让我卡住了。如果我的代码结构看起来像这样,如何实现约束?这合法吗?谢谢你。

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    
}
4

1 回答 1

2
 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");
    }
}

现在制作基类

public abstract class CrtpBaseWrapper<T> : MyBase
    where T : CrtpBaseWrapper<T>
{
}

然后你可以制作你的子类

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");
    }
}
于 2014-01-22T11:45:19.923 回答