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

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

c# - Explicit implementation of an interface using an automatic property

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...