簡體   English   中英

使用自動屬性的接口的顯式實現

[英]Explicit implementation of an interface using an automatic property

有什么方法可以使用自動屬性來顯式實現接口嗎? 例如,考慮以下代碼:

namespace AutoProperties
{
    interface IMyInterface
    {
        bool MyBoolOnlyGet { get; }
    }

    class MyClass : IMyInterface
    {
        static void Main(){}

        public bool MyBoolOnlyGet { get; private set; } // line 1
        //bool IMyInterface.MyBoolOnlyGet { get; private set; } // line 2
    }
}

這段代碼會編譯。 但是,如果將第1行替換為第2行,則不會編譯。

(並不是我需要使第2行正常工作-我只是很好奇。)

實際上,該語言不支持這種特定的安排(通過自動實現的屬性明確實現僅獲取接口的屬性)。 因此, 要么手動(帶有字段)執行,要么編寫一個私有的自動實現的道具,然后代理它。 但老實說,當您完成操作時,您可能已經使用了一個字段...

private bool MyBool { get;set;}
bool IMyInterface.MyBoolOnlyGet { get {return MyBool;} }

要么:

private bool myBool;
bool IMyInterface.MyBoolOnlyGet { get {return myBool;} }

問題在於該接口只有getter,您嘗試使用getter和setter顯式實現它。
當您顯式實現接口時,僅當引用為接口類型時才調用顯式實現,因此...如果接口僅具有getter,則無法使用setter,因此在那里沒有setter是沒有意義的。

例如,這將編譯:

namespace AutoProperties
    {
        interface IMyInterface
        {
            bool MyBoolOnlyGet { get; set; }
        }

        class MyClass : IMyInterface
        {
            static void Main() { }

            bool IMyInterface.MyBoolOnlyGet { get; set; } 
        }
    }

暫無
暫無

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

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