Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

c# - Scaleable Fluent Interface with Inheritance

I am trying to write a Fluent Interface API that can scale well. What structure would allow for strong types, inheritance, and state-full(as in the class type)?

For instance

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

 }

I would like class B when calling PerformFoo to return B not A, ideally I would prefer to stay away from

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

As to not have to override or new Every method in child classes. I believe I would need to use generics that use Type signatures.

I don't want to use extension methods but can't seem to get the structure right when doing it with casting (T) like in the answer for [a link]Fluent interfaces and inheritance in C#

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understand correctly, the issue is that Method1 is not behaving the way you'd like, as it downcasts to A, preventing you from calling further methods. One way around this is to shadow the method in subclasses:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...