【发布时间】:2017-11-11 20:07:03
【问题描述】:
同样的问题as this one,但针对 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;
}
}
解决方法:
class MyPerson : IPerson
{
string _name;
string IPerson.Name { get { return _name; } }
internal MyPerson(string withName)
{
_name = withName;
}
}
【问题讨论】:
-
我认为你可以将属性实现为
string IPerson.Name { get; private set; }编辑:经过测试,结果我错了。 -
@itsme86 不幸的是,您不能使用显式接口实现 -
IPerson.Name。如果他不使用对IPerson的显式引用,他可以,但有时由于名称重复/冲突,您需要显式调用