简体   繁体   中英

How to forbid using property setter?

[KnownType(typeof(B))]
public abstract class A: IA //  string Description { get; }
{
      [DataMember(Name = "description")]
      public virtual string Description { get; set; }
}

public sealed class B: A
{
    public override string Description
    {
        get
        {
            return "Custom_Description";
        }
    }
}

I cannot change my abstract class and I want to forbid using set in Description like:

B b = new B();
b.Description = "description";

How to do that? How can I implement set ?

I think your best option is to throw a NotSupportedException in the set accessor:

public sealed class B : A {
    public override string Description {
        get {
            return "Custom_Description";
        }
        set {
            throw new NotSupportedException();
        }
    }
}

If you want to get a compile error, instead, that's not possible, as you cannot change the accessibility of the set method in B . Even if you could, someone could cast your instance of B to a type A and call set on it.

Here are two ways.

  1. Just make setter protected.

     public abstract class A: IA { public virtual string Description { get; protected set; } } 

    This guarantees that 90% of your code can't set Description. But in inheritors of class A you still can try to set Description . And it's compile-time safety

  2. Replace original auto-property to abstract property without setter. Then in class B write implementation for that. And in some another class you can create backing field if you want to have ability to set/get property. This is more secure way, but it can lead you to redudant copy-paste code.

If it is in you abstract class I think it cannot be done. An ugly work around would be:

public sealed class B: A
{
    public override string Description
    {
        get
        {
            return "Custom_Description";
        }
        set
        {
           throw new InvalidOperationException();
        }
    }
}

You can also discard (take it, but not use it) the value in the setter

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