2013-04-20 56 views
0

我试图实现CRTP接口到我的代码,但约束让我卡住了。如何实现约束如果我有代码结构看起来像这样?这合法吗?谢谢。c#中多重好奇的循环模板模式(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

您是否尝试过编译代码?如果它没有编译,你会得到什么错误? – svick 2013-04-20 23:09:17

+0

即使编译器允许它(所有的代码都是错的:)('interface IInterface where T:IInterface 'et al)。我认为你最好解释你想要什么,你有什么结构。 – NSGaga 2013-04-21 01:05:15

+0

@svick如果代码写得那样,我没有任何错误。但是,当我试图增加约束条件时,会让我头疼.ITest1 :实体其中iTest2:ITest2 ,ITest3 ,..... (?????)' – user2277061 2013-04-21 09:46:09

回答

1
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"); 
    } 
} 
+0

终于我用你的方法。谢谢 – user2277061 2014-02-04 07:11:40