开发者

C#, read / write separation and properties. Pattern required

Ok, so C# has properties

public int Prop {get;set;}

I can put the getter and the setter on separate interfaces like this:

public interface IRead
{ int AnInt { get; } }

public interface IWrite
{ int AnInt { set; } }

And then mix and match them like so:

public class WorkingClass : IRead, IWrite
{
    public int AnInt { get; set; }
}

Where it starts to go wrong is where I might have a base object.

public class BaseClass : IRead
{
    private int _anInt;

    public BaseClass(int anInt)
    { _anInt = anInt; }

    public virtual int AnInt
    { get { return _anInt; } }
}

I then want a derived class which can write as well.

public class Derived : BaseClass, IWrite //bits elided
{
    public override int AnInt
    {
        get { return base.AnInt; }
        set { throw new NotImplementedException(); } //<-- error
    }
}

Which of course doesn't work.

This actually doesn't come up that often. I prefer to have methods with change state and have properties read only. This is design 101 I guess, but as a contrived example, I'd have an Age property with just a get and then a method called IncreaseAge.

So with that all in mind. If you did want to have a mutable object with seperate read and write interfaces how would yo开发者_如何学Gou do it?

I could do it in a Java-esque way with separate getter/setter methods on each interface. But that negates the benefits of properties + one of the cop programs will yell at me.


You can have the base setter protected and have the derived class implement IWrite explicitly delegating to the base setter:

public class BaseClass : IRead {
  public BaseClass(int anInt) { AnInt = anInt; }

  public int AnInt {
    get; protected set;
  }
}

public class Derived : BaseClass, IWrite {
  public Derived(int anInt) : base(anInt) { }

  int IWrite.AnInt {
    set { base.AnInt = value; }
  }
}

(The keyword base can even be omitted and the base property doesn't need to be virtual.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜