Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there any way to implement an interface explicitly using an automatic property? For instance, consider this code:

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
    }
}

This code compiles. However, if you replace line 1 with line 2 it does not compile.

(It's not that I need to get line 2 working - I'm just curious.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
497 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;} }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...