Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...