简体   繁体   中英

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"

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 . Also you could not add set property as it does not exist in the 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";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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