开发者

Read-only properties inheritance: abstract or set-protected

开发者 https://www.devze.com 2023-04-04 08:22 出处:网络
Let\'s say that class A is abstract and defines read-only properties that class B, which inherits from it, must provide. Is it better practice to define such properties as abstract or as set-protected

Let's say that class A is abstract and defines read-only properties that class B, which inherits from it, must provide. Is it better practice to define such properties as abstract or as set-protected:

public abstract class A
{
    public abstract int Value { get; }
}
public class B : A
{
    public override int Value { get { return 1; } }
}

OR

public abstract class A
{
    public int Value { get; protected set; }
}
public class B : A
{
    publ开发者_如何学运维ic B()
    {
        Value = 1;
    }
}

I think that the first solution is probably better but i'd like to hear other opinions.


It depends on what you mean by read-only. If you mean read-only for callers, then I would prefer the second solution.

The first solution forces the child class to implement get, which is good. But it prohibits the child from implementing set (even a protected one), which is bad.

With the second solution, the whole Value interface is defined by the base class, which is good, and the child class is still able to set Value when it chooses, which is also good.

If on the other hand by "read-only" you mean truly read-only, in that not even the child class is allowed to set Value, then the first solution is better. You even get the right compile error if you do try to set it.

0

精彩评论

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

关注公众号