问题
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.)
回答1:
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;} }
回答2:
The problem is that the interface has only getter and you try to explicitly implement it with getter and setter.
When you explicitly implement an interface the explicit implementation will be called only when your reference if of the interface type, so... if the interface only has getter there is no way to use the setter so it makes no sense to have a setter there.
This, for example will compile:
namespace AutoProperties
{
interface IMyInterface
{
bool MyBoolOnlyGet { get; set; }
}
class MyClass : IMyInterface
{
static void Main() { }
bool IMyInterface.MyBoolOnlyGet { get; set; }
}
}
来源:https://stackoverflow.com/questions/3905000/explicit-implementation-of-an-interface-using-an-automatic-property