简体   繁体   English

如何使用公共属性而不是私有集合方法实现多个接口?

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

I have two interfaces: 我有两个界面:

public interface IFooFile
{
    string Name { get; }
}

public interface IFooProduct
{
    string Name { get; }
}

I'm wanting to implement both with private sets: 我想用私有集实现这两个:

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

But the access modifiers are creating the error: 但是访问修饰符正在创建错误:

The accessor of the "AFooThing.IFooFile.Name.set" must be more restrictive than the property or indexer "AFooThing.IFooFile.Name" “ AFooThing.IFooFile.Name.set”的访问者必须比属性或索引器“ AFooThing.IFooFile.Name”更具限制性。

If I implement the class like this, I get no access modifier errors but I don't have the second interface: 如果我实现这样的类,则不会出现访问修饰符错误,但没有第二个接口:

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

I can't figure out how to have both interfaces implemented with the added "private set" without causing problems. 我无法弄清楚如何用添加的“私有集”实现两个接口而不会引起问题。 What is the proper way to handle this? 处理此问题的正确方法是什么?

You cannot use access modifiers for an explicit interface, it is public . 您不能将访问修饰符用于显式接口,它是public Also you could not add set property as it does not exist in the interface . 您也不能添加set属性,因为它在interface中不存在。 What you can do is achieve your goal by using backing fields, eg 您可以做的是通过使用备用字段来实现您的目标,例如

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";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM