簡體   English   中英

使用接口公開方法鏈中的特定方法

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

在Client類中,我的“測試”實例僅限於Init()和Method3()方法,但是在方法鏈中使用時,所有方法都是可以訪問的。 當我希望客戶端使用方法鏈時,如何使用接口來限制可訪問的方法?

我還應該提到,可能還有另一個接口僅公開另一組特定方法:

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

嘗試將方法返回類型更改為InterfaceTest1

例如,將您的界面更改為:

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

為以下方法更改InterfaceTestBuilder類的實現:

public InterfaceTest1 Init()
{

    return this;
}
public InterfaceTest1 Method3()
{

    return this;
}

然后,您將無法進行以下調用,因為調用Init之后將無法訪問Method1

    InterfaceTest1 test = new InterfaceTestBuilder();

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM