相关疑难解决方法(0)

自反型参数约束:X <T>其中T:X <T> - 任何更简单的替代方案?

我经常通过向它添加自引用("反身")类型参数约束来使一个简单的界面变得更加复杂.例如,我可能会这样:

interface ICloneable
{
    ICloneable Clone();
}

class Sheep : ICloneable
{
    ICloneable Clone() { … }
} //^^^^^^^^^^

Sheep dolly = new Sheep().Clone() as Sheep;
                                //^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

成:

interface ICloneable<TImpl> where TImpl : ICloneable<TImpl>
{
    TImpl Clone();
}

class Sheep : ICloneable<Sheep>
{
    Sheep Clone() { … }
} //^^^^^

Sheep dolly = new Sheep().Clone();
Run Code Online (Sandbox Code Playgroud)

主要优点:实现类型(例如Sheep)现在可以引用自身而不是其基类型,从而减少了对类型转换的需求(如最后一行代码所示).

虽然这非常好,但我也注意到这些类型参数约束并不直观,并且在更复杂的场景中变得非常难以理解.*)

问题:有没有人知道另一种C#代码模式可以实现相同的效果或类似的东西,但是更容易掌握?


*)此代码模式可能不直观且难以理解,例如以下方式:

  • 声明X<T> where T : X<T>似乎是递归的,人们可能想知道为什么编译器不会陷入无限循环,推理,"如果TX<T>,那么X<T>实际上是一个 …

c# generics crtp type-constraints self-reference

18
推荐指数
2
解决办法
1376
查看次数

标签 统计

c# ×1

crtp ×1

generics ×1

self-reference ×1

type-constraints ×1