Make readonly property in derived class

I am overriding a property in my derived class that I would like to make it read-only. The C # compiler won't let me change access modifiers, so it should stay open.

What is the best way to do this? Should I just throw InvalidOperationExceptionin set { }?

+5
source share
6 answers

Having setter throw InvalidOperationExceptionin a derived class violates the Liskov Subscription Principle . Essentially makes the use of the setter contextual for a base class type that substantially eliminates the meaning of polymorphism.

. , .

- .

class C1 { 
  public virtual int ReadOnlyProperty { get; } 
}
class C2 { 
  public sealed override int ReadOnlyProperty { 
    get { return Property; }
  }
  public int Property {
    get { ... }
    set { ... }
  }
}

, , C1 , C2

+8

:

class Foo
{
    private string _someString;
    public virtual string SomeString 
    {
        get { return _someString; }
        set { _someString = value; }
    }
}

class Bar : Foo
{
    public new string SomeString 
    { 
        get { return base.SomeString; }
        private set { base.SomeString = value; }
    }
}

namespace ConsoleApplication3
{
    class Program
    {
        static void Main( string[] args )
        {
            Foo f = new Foo();
            f.SomeString = "whatever";  // works
            Bar b = new Bar();
            b.SomeString = "Whatever";  // error
        }
    }
}

,. , . ?

+3

,

public class Aclass {        
    public int ReadOnly { get; set; }
}

public class Bclass : Aclass {        
    public new int ReadOnly { get; private set; }
}
+1

#, - , .

, , , , . " " , "" - " " , . " " .

0

Setter . , , mjfgates, , . Thats .

0

, , , . , MaybeMutableFoo, MutableFoo ImmutableFoo. IsMutable AsMutable(), AsNewMutable() AsImmutable().

, MaybeMutableFoo read-write, , , IsMutable true. , MaybeMutableFoo, ImmutableFoo, , , , AsMutable(), foo ( , , ). MaybeMutableFoo setter, - , .

- , , .

public class MaybeMutableFoo
{
    public string Foo {get {return Foo_get();} set {Foo_set(value);}
    protected abstract string Foo_get();
    protected abstract void Foo_set(string value};
}

ImmutableFoo :

    new public string Foo {get {return Foo_get();}

Foo , Foo_get() Foo_set(). , Foo get; , , , . , getter setter, , .

0

All Articles