【问题标题】:Scaleable Fluent Interface with Inheritance具有继承的可扩展流畅接口
【发布时间】:2014-09-07 13:29:35
【问题描述】:

我正在尝试编写一个可以很好扩展的 Fluent Interface API。什么结构允许强类型、继承和状态全(如在类类型中)?

例如

 class A
 {
     public A PerformFoo()
     {
         //do stuff
         return this;
     }
 }
 class B : A
 {

 }

我希望 B 类在调用 PerformFoo 时返回 B 而不是 A,理想情况下我宁愿远离

public class B : A
{
    public new B PerformFoo()
    {
        return (B)base.PerformFoo();
    }
}

至于不必重写或新建子类中的 Every 方法。我相信我需要使用使用类型签名的泛型。

我不想使用扩展方法,但在使用强制转换 (T) 时似乎无法获得正确的结构,就像 [a link]Fluent interfaces and inheritance in C# 的答案中一样。

【问题讨论】:

  • 您实际上并没有问过问题……您只是给出了一些代码,以及一些调用它的代码。有什么问题?

标签: c# inheritance interface fluent


【解决方案1】:

如果我理解正确,问题是 Method1 的行为方式不符合您的要求,因为它向下转换为 A,从而阻止您调用更多方法。解决这个问题的一种方法是在子类中隐藏方法:

public class A
{
    public A Method1()
    {
        return this;
    }
}

public class B : A
{
    public new B Method1()
    {
        return (B)base.Method1();
    }
}

【讨论】:

  • 不幸的是,它不能很好地扩展以使子类中的每个方法都嵌套覆盖基本案例中的每个共享方法
【解决方案2】:

终于弄明白了结构

public class A {}
public class B : A {}
public class C<T> : A where T : C<T>
{/*most methods return T*/}
public class D:C<D>
{/*all methods return this*/}
public class E<T>:C<T> where T:E<T>
{/*all methods return T*/}
public class F:E<F>{}

现在即使是专门的泛型仍然会返回原来的调用者

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    相关资源
    最近更新 更多