简体   繁体   中英

Can Get/Set accessors of property to be in different interfaces?

I want something like the next:

interface INamedObject
{
    string Name { get; }
}

interface IRenamableObject : INamedObject
{
    string Name { set; }
}

In words, I want to create two interfaces, one of which contains get accessor for property and another - set accessor. Can I do this in C#?

(The code compiles but the compiler gives the following warning:)

'IRenamableObject.Name' hides inherited member 'INamedObject.Name'. Use the new keyword if hiding was intended.

Sure you can:

interface INamedObject
{
    string Name { get; }
}

interface IRenamableObject : INamedObject
{
    new string Name { set; }
}

class SomeObject : IRenamableObject
{
    public string Name { get; set;  }
}

// usage:
IRenamableObject obj = new SomeObject();
obj.Name = "some name";
Console.WriteLine((obj as INamedObject).Name);

Is it a good idea? I wouldn't want it in my code. It seems to me that when you get oddities like this, perhaps it indicates that there is a design flaw somewhere. One indication is that you do get a warning that Name in one of the interfaces shadows the other, so you need the new keyword, which I typically feel is a workaround more than a solution.

Note that the interfaces can be completely decoupled from each other:

interface INamedObject
{
    string Name { get; }
}

interface IRenamableObject
{
    string Name { set; }
}

This would remove the shadowing issue. It would also allow you to have an object with a Name property that is write-only which is also a tad strange...

The property defined in IRenamableObject will hide the one in INamedObject . You need to use

interface IRenamableObject : INamedObject
{
    new string Name { get; set; }
}

Yes, you can have Get and Set properties in two different interfaces.

But, main question is Why do you need it that way?

it compiles, doesn't mean that it's a correct design.

interface INamedObject 
{     
    string Name { get; } 
}

interface IRenamableObject //: INamedObject No need to inherit
{     
    string Name { set; } 
} 

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