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

C# 使用自动属性显式实现接口,c#,automatic-properties,C#,Automatic Properties,有没有办法使用自动属性显式实现接口?例如,考虑这个代码: namespace AutoProperties { interface IMyInterface { bool MyBoolOnlyGet { get; } } class MyClass : IMyInterface { static void Main(){} public bool MyBoolOnlyGet { get; private

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

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行工作——我只是好奇。)

事实上,这种特殊的安排(通过自动实现的属性显式实现get-only接口属性)不受语言支持。因此,要么手动执行(使用字段),要么编写一个私有的自动实现的道具,并为其代理。但老实说,当你这么做的时候,你可能已经使用了一个领域

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


问题是接口只有getter,您试图用getter和setter显式实现它。
当显式实现接口时,仅当引用if为接口类型时,才会调用显式实现,因此。。。如果接口只有getter,则无法使用setter,因此在那里使用setter是没有意义的

例如,这将编译:

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

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

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

对于“为什么”-问问你自己。。。我该如何分配它?我有两个错误:1AutoProperties.MyClass.AutoProperties.IMyInterface.MyBoolOnlyGet.set'添加在接口成员AutoProperties.IMyInterface.MyBoolOnlyGet'中找不到的访问器。2.修饰符“private”对此项无效。我看不出这可以解释为什么显式实现接口比隐式实现更受限制。如果隐式实现导致C#编译器自动为您生成必要的显式实现代码,那么这可能是有意义的。你能在这里弥合逻辑鸿沟吗?是什么让隐式与显式不同,从而破坏了OP的代码?假设你可以在显式实现中定义这样的私有setter。你怎么用它?”this.setter=…'将委托给隐式setter(因为这是MyClass类型),而“((IMyInterface)this.setter”将失败,因为IMyInterface没有定义setter。这就是全部要点。如果显式实现的属性可以自动实现,那么我就不必为它手动实现自己的备份存储。我还可以依靠接口定义一个getter来隐藏我的私有setter。嗯,我想这是有问题的,但在我看来,这基本上是一个问题。您应该能够告诉编译器,只有setter或getter在实现显式接口。
namespace AutoProperties
    {
        interface IMyInterface
        {
            bool MyBoolOnlyGet { get; set; }
        }

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

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