在构造函数中为显式实现的只读接口 属性 赋值

Assign a value to an explicitly-implemented readonly interface property in a constructor

同样的问题 ,但对于 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; 
    }
}

不,您仍然需要在 C# 7 中使用相同的解决方法。如果您指的是将表达式主体成员扩展到构造函数,则解除此限制没有任何效果。

从 C# 7 开始,您可以做的最好的事情就是利用表达式主体属性和构造函数来稍微简化您的代码:

class MyPerson : IPerson
{
    string _name;
    string IPerson.Name => _name;

    internal MyPerson(string withName) => _name = withName;
}

虽然这并没有直接解决您的问题:有一种方法可以从构造函数中设置接口显式 属性。尽管有人提议 可能会 将来解决这个问题,但不能保证。

Proposal: Property-Scoped Fields,这表明允许在属性中使用上下文关键字 field 来引用支持字段,而不必明确定义后者。这也可能提供如下语法:

string IPerson.Name { get; }
internal MyPerson(string withName) => IPerson.Name.field = withName;

不过,以上link只是GitHub上C#语言库的一个讨论话题。我还没有(还)被语言团队 "championed",这是它甚至被视为新功能的第一步。所以很有可能这永远不会被添加到语言中(但事情有时会违背可能性,所以永远不要说永远......)