簡體   English   中英

需要由第三方實現的C#接口

[英]C# Interface that needs to be implemented by a third-party

我正在為第三方用戶開發API,但遇到了麻煩:

該API如下所示:

public interface IFoo
{
    Init(IComponent component);

    ...
}

該接口需要由第三方實現,但是我們將調用Init方法。 我的問題是,我將傳遞一個IComponent實例給他們,他們可以在Init方法中使用它們,但不應在其他任何地方使用它們。

是否有可能進行這樣的運行時檢查以確保它們沒有保存它,或者以某種方式組織這種行為,使得無法從Init方法中使用該IComponent實例?

我認為您不能直接控制在任何地方實現Init()的方式。 但是,您的IComponent可能會像需要的那樣偷偷摸摸,執行類似下面的代碼的操作將使插件在事發后無法使用實例。

public interface IComponent
{
    void DoSomething();
}

class Component : IComponent
{
    bool flag;

    public DoSomething()
    {
        if( flag )
            throw new NotSupportedException( "Operation not supported anymore." );
        // Do something normal during Init().
    }

    internal void MarkCOmplete()
    {
        flag = true;
    }
}

....

void Initialize()
{
    var component = new Component();

    foreach(var plugin in plugins)
    {
        plugin.Init(component);
    }
    component.MarkComplete();
}

暫無
暫無

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

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