显式实现接口的使用自动属性 [英] 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
}
}
此代码编译。但是,如果你有2号线更换1号线就不能编译。
This code compiles. However, if you replace line 1 with line 2 it does not compile.
(这并不是说我需要得到2号线的工作 - 我只是好奇)
(It's not that I need to get line 2 working - I'm just curious.)
推荐答案
实际上,该特定排列(用自动实现属性显式实现一个get-只接口属性的)不被支持的语言。所以的或者的做手工(与字段),或写私人自动实现的道具,和代理它。不过说实话,你的时间这样做,你还不如用一个字段...
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;} }
或
private bool myBool;
bool IMyInterface.MyBoolOnlyGet { get {return myBool;} }
这篇关于显式实现接口的使用自动属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!