有没有办法使用自动属性显式实现接口?例如,考虑以下代码:
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
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码编译.但是,如果将第1行替换为第2行,则无法编译.
(这不是我需要让第2行工作 - 我只是好奇.)
与此问题相同,但对于C#7.0而不是6.0:
有没有办法在构造函数中为显式实现的只读(仅限getter)接口属性赋值?或者它仍然是相同的答案,即使用支持领域的解决方案?
例如:
interface IPerson
{
string Name { get; }
}
class MyPerson : IPerson
{
string IPerson.Name { get; }
internal MyPerson(string withName)
{
// doesn't work; Property or indexer 'IPerson.Name'
// cannot be assigned to --it is read only
((IPerson)this).Name = withName;
}
}
Run Code Online (Sandbox Code Playgroud)
解决方法:
class MyPerson : IPerson
{
string _name;
string IPerson.Name { get { return _name; } }
internal MyPerson(string withName)
{
_name = withName;
}
}
Run Code Online (Sandbox Code Playgroud) 我读过自动实现的属性不能只读或只写.它们只能是读写的.
然而,在学习界面时,我遇到了foll.代码,它创建只读/只写和读写类型的自动属性.那可以接受吗?
public interface IPointy
{
// A read-write property in an interface would look like:
// retType PropName { get; set; }
// while a write-only property in an interface would be:
// retType PropName { set; }
byte Points { get; }
}
Run Code Online (Sandbox Code Playgroud)