如何实现具有 public 属性但私有设置方法的多个接口?

How do I implement multiple interfaces with public properties but private set methods?

我有两个接口:

public interface IFooFile
{
    string Name { get; }
}

public interface IFooProduct
{
    string Name { get; }
}

我想用私有集来实现:

public class AFooThing : IFooFile, IFooProduct
{
    public string IFooFile.Name { get; private set; }
    public string IFooProduct.Name { get; private set; }
}

但是访问修饰符造成了错误:

The accessor of the "AFooThing.IFooFile.Name.set" must be more restrictive than the property or indexer "AFooThing.IFooFile.Name"

如果我这样实现 class,我不会收到访问修饰符错误,但我没有第二个接口:

public class AFooThing : IFooFile
{
    public string Name { get; private set; }
}

我不知道如何在不引起问题的情况下使用添加的 "private set" 实现两个接口。处理这个问题的正确方法是什么?

您不能对显式接口使用访问修饰符,它是 public。此外,您无法添加 set 属性,因为它不存在于 interface 中。您可以做的是通过使用支持字段来实现您的目标,例如

public class AFooThing : IFooFile, IFooProduct
{
    private string _fooFileName;
    private string _fooProductName;

    string IFooFile.Name => _fooFileName;
    string IFooProduct.Name => _fooProductName;

    public AFooThing()
    {
        _fooFileName = "FooFileName";
        _fooProductName = "FooProductName";
    }
}