简体   繁体   中英

Using an interface to expose specific methods in a method chain

namespace ScratchPad
{
    public class InterfaceTestBuilder : InterfaceTest1
    {
        public InterfaceTestBuilder Init()
        {

            return this;
        }

        public InterfaceTestBuilder Method1()
        {

            return this;
        }

        public InterfaceTestBuilder Method2()
        {

            return this;
        }

        public InterfaceTestBuilder Method3()
        {

            return this;
        }

    }

    public interface InterfaceTest1
    {
        InterfaceTestBuilder Init();
        InterfaceTestBuilder Method3();
    }

    public class Client
    {
        public void TestMethod1()
        {
            InterfaceTest1 test = new InterfaceTestBuilder();

            test.Init();
                    test.Method3();
            test.Init().Method1().Method2().Method3();
        }
    }
}

In the Client class, my "test" instance is limited to just the Init() and Method3() methods, however when used in a method chain all methods are accessible. How can I use an Interface to limit what methods are accessible when I want my client to use a method chain?

I should also mention that there could be another Interface that only exposes another set of specific methods:

public interface InterfaceTest2
{
    InterfaceTestBuilder Init();
    InterfaceTestBuilder Method1();
}

Try changing the method return types to InterfaceTest1

For example, change your interface to:

public interface InterfaceTest1
{
    InterfaceTest1 Init();
    InterfaceTest1 Method3();
}

Changing your InterfaceTestBuilder class implementation for the following methods:

public InterfaceTest1 Init()
{

    return this;
}
public InterfaceTest1 Method3()
{

    return this;
}

You will then not be able to make the following calls, as Method1 will not be accessible after calling Init :

    InterfaceTest1 test = new InterfaceTestBuilder();

    test.Init().Method1().Method2().Method3();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM