使用自动属性显式实现接口

use*_*813 14 c# automatic-properties

有没有办法使用自动属性显式实现接口?例如,考虑以下代码:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码编译.但是,如果将第1行替换为第2行,则无法编译.

(这不是我需要让第2行工作 - 我只是好奇.)

Mar*_*ell 15

实际上,该语言不支持该特定安排(由自动实现的属性显式实现get-only接口属性).所以要么手动(使用字段),要么写一个私有的自动实现的prop,并代理它.但说实话,当你完成这项工作时,你可能已经使用了一个领域......

private bool MyBool { get;set;}
bool IMyInterface.MyBoolOnlyGet { get {return MyBool;} }
Run Code Online (Sandbox Code Playgroud)

要么:

private bool myBool;
bool IMyInterface.MyBoolOnlyGet { get {return myBool;} }
Run Code Online (Sandbox Code Playgroud)


Ita*_*aro 5

问题是接口只有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; } 
        }
    }
Run Code Online (Sandbox Code Playgroud)