【问题标题】:Explicit implementation of an interface using an automatic property使用自动属性显式实现接口
【发布时间】:2010-10-11 09:31:14
【问题描述】:

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

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

【问题讨论】:

  • 对于“为什么”——问问自己...我将如何分配它?
  • 我收到两个错误:1. 'AutoProperties.MyClass.AutoProperties.IMyInterface.MyBoolOnlyGet.set' 添加了一个在接口成员 'AutoProperties.IMyInterface.MyBoolOnlyGet' 中找不到的访问器。 2. 修饰符“private”对此项无效

标签: c# automatic-properties


【解决方案1】:

确实,该语言不支持这种特殊安排(通过自动实现的属性显式实现 get-only 接口属性)。所以要么手动(使用字段),或者编写一个私有的自动实现的道具,并代理它。但老实说,当你这样做的时候,你还不如使用一个字段......

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

或:

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

【讨论】:

    【解决方案2】:

    问题在于接口只有 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; } 
            }
        }
    

    【讨论】:

    • 我没有看到这解释了为什么显式实现接口应该比隐式实现更受限制。如果隐式实现导致 C# 编译器自动为您生成必要的显式实现代码,这也许是有意义的。您能否弥补这里的逻辑鸿沟——究竟是什么让隐式与显式不同,从而破坏了 OP 的代码?
    • 假设您可以在显式实现中定义这样的私有设置器。你会如何使用它? 'this.setter = ...' 将委托给隐式 setter(因为 this 是 MyClass 类型),而 '((IMyInterface) this).setter' 将失败,因为 IMyInterface 没有定义 setter。
    • 这就是重点。如果显式实现的属性可以自动实现,那么我就不必为它手动实现我自己的后备存储。我也可以依靠只定义一个 getter 的接口来隐藏我的私有 setter。好吧,我猜这有问题,但在我看来,这与unable to override just a property’s setter or getter 基本相同。您应该能够告诉编译器只有您的 setter 或您的 getter 正在实现显式接口。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    相关资源
    最近更新 更多