c#中的多重奇怪循环模板模式(CRTP)
本文关键字:模式 CRTP 循环 | 更新日期: 2023-09-27 18:10:14
我试图实现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
}
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");
}
}