Explicit implementation of an interface using an automatic property

让人想犯罪 __ 提交于 2019-11-29 09:19:51

Indeed, that particular arrangement (explicit implementation of a get-only interface property by an automatically implemented property) isn't supported by the language. So either do it manually (with a field), or write a private auto-implemented prop, and proxy to it. But to be honest, by the time you've done that you might as well have used a field...

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

or:

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

The problem is that the interface has only getter and you try to explicitly implement it with getter and setter.
When you explicitly implement an interface the explicit implementation will be called only when your reference if of the interface type, so... if the interface only has getter there is no way to use the setter so it makes no sense to have a setter there.

This, for example will compile:

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

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

            bool IMyInterface.MyBoolOnlyGet { get; set; } 
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!