【问题标题】:multiple curiously recurring template pattern (CRTP) in c#?c# 中的多个奇怪重复的模板模式(CRTP)?
【发布时间】:2013-04-20 22:46:00
【问题描述】:

我正在尝试为我的代码实现 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    
}

【问题讨论】:

  • 你试过编译你的代码吗?如果它没有编译,你会得到什么错误?
  • 该代码全错 :) 即使编译器允许(interface IInterface&lt;T&gt; where T : IInterface&lt;T&gt; 等)。我认为你最好解释你想要什么,你有什么结构。
  • @svick 如果代码是这样写的,我没有任何错误。但是当我尝试添加约束时,会让我头疼。ITest1&lt;iTest2, iTest1&gt; : Entity&lt;iTest1&gt; where iTest2 : ITest2&lt;ITest1&lt;iTest2,iTest1&gt;,ITest3&lt;ITest1&lt;iTest2,iTest1&gt;,..... (?????)
  • @NSGaga 我读过 Eric Lippert 的博客,他说:> class Blah&lt;T&gt; where T : Blah&lt;T&gt; > 这似乎在(至少)两个方面是循环的。这真的合法吗? > 是的,它是合法的,并且确实有一些合法用途……在我的例子中,我有 2 个玩家,每个玩家有 10 个棋子。每个棋子都将放置在 5 x 5 的棋盘上。棋盘上的每个点都有不同的移动参考。像这样的映射。每个棋子都会从他们的点复制移动参考。 thumbnails101.imagebam.com/25012/afd0fd250112805.jpg?nc
  • @user2277061 我认为这听起来不像是你应该使用类型系统建模的东西。

标签: c# crtp recurring


【解决方案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");
    }
}

【讨论】:

  • 最后我用了你的方法。谢谢
猜你喜欢
  • 2022-01-01
  • 2013-02-15
  • 2019-11-18
相关资源
最近更新 更多