开发者

Interfaces with different getter and setter for the same propertie

I've made the following decl开发者_JS百科aration for interfaces:

public interface IBasic
{
  int Data { get; }
}

public interface IChangeable : IBasic
{
  int Data { set; }
}

The compiler says that IChangeable.Data hides IBasic.Data. It's reasonable. The alternative I've found is:

public interface IBasic
{
  int Data { get; }
}

public interface IChangeable : IBasic
{
  void ChangeData(int value);
}

There is any way to define setter and getters for the same property on different hierarchy on interfaces? Or there are any alternatives to this approach?


You can re-declare it (or rather, tell the compiler that you intend to hide it):

public interface IChangeable : IBasic
{
  new int Data { set; }
}
class Foo : IChangeable
{
    private int value;
    int IBasic.Data { get { return value; } }
    int IChangeable.Data { set {this.value = value;}  }
}

But this is confusing, and you'll need to use explicit implementations etc, and probably a bit of casting at the caller if you want to use the hidden version. If you went this route, I would recommend exposing both the get and set on IChangeable:

public interface IChangeable : IBasic
{
    new int Data { get;  set; }
}
class Foo : IChangeable
{
    private int value;
    int IBasic.Data { get { return value; } }
    int IChangeable.Data { set { this.value = value; } get {return value; } }
}

Re the comments; to expose on the implementing type:

public interface IChangeable : IBasic
{
    new int Data { set; }
}
public interface IBasic
{
    int Data { get; }
}
class Foo : IChangeable
{
    private int data;
    public int Data {
        get { return data; }
        set { data = value; }
    }
}

This would also work if you make it (which I prefer):

public interface IChangeable : IBasic
{
    new int Data { get; set; }
}


Maybe I've misunderstood your question but wouldn't you just do

public interface IChangeable : IBasic
{
  int Data { get; set; }
}

i.e. Let IChangeable override the property but keep the "get" present.

As IChangeable inherits from IBasic I'm assuming you want an implementation of IChangeable to have an implementation of "get".


I think GetData and SetData methods is more clear for this situation:

public interface IBasic
{  
    int GetData();
}

public interface IChangeable : IBasic
{  
    void SetData(int data)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜