我试图为我的代码实现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
}
答案 0 :(得分: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");
}
}