c# - 使用自动属性显式实现接口(interface)

标签 c# automatic-properties

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

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

最佳答案

确实,该语言不支持该特定安排(通过自动实现的属性显式实现只获取接口(interface)属性)。因此,要么手动执行(使用字段),要么编写一个私有(private)的自动实现的 prop,并为其代理。但老实说,当您完成这些操作时,您还不如使用一个字段...

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

或:

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

关于c# - 使用自动属性显式实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3905000/

相关文章:

c# - 虚拟路径 '/' 映射到另一个应用程序,这是不允许的。 MVC 和 Hangfire

c# - 调用 INotifyPropertyChanged 的​​ PropertyChanged 事件的最佳方式是什么?

c# - 从变量快速创建 C# 属性

C# 3.0 Auto-Properties - 是否可以添加自定义行为?

vb.net - VB.NET 中有自动属性的代码片段吗?

c# - 在 C# 中表达 AND NOT 运算符的正确方法是什么?

c# - 将 IsEnabled 属性绑定(bind)到 WPF 中的 bool 值

c# - 如何在 Linq toEntity 中将字符串数组转换为字符串?

没有私有(private)变量的 C# 自定义 getter/setter

C# Lambda 性能问题/可能性/指南