开发者

How to prevent hide or override on a public property

I have an abstract base class that has a Property on it that I would like to prevent both hiding, aka new, and override on.

public abstract class DomainObject
{
    publ开发者_C百科ic bool IsDeleted { get; set; }
}

public class BankAccount : DomainObject
{
    public bool IsDeleted { get; set; }
}

The issue is: I need BankAccount to inherit from the base DomainObject class, so I can't mark it as sealed, but I want to prevent the situation, an override or new, of IsDeleted at compile time.


In this case IsDeleted is not virtual so an override is not possible. In general though you can prevent the override case by not making a property virtual in the first place or preventing further overrides by specifying the sealed modifier on the property

public sealed override IsDeleted { get; set; }

However you can't prevent the hiding via new. There is no way to prevent a sub-type from using new on an existing property other than preventing sub-types altogether


I've had this same need for the same reason that you mentioned in comments: preventing issues caused by generated code. My solution was to make this specific warning an error, which can be done by adding "0108" to the "Project Properties" => "Build" => "Treat warnings as errors" => "Specific warnings" list.

I'd be curious to know why this was considered to be only a warning and not an error in the first place. Surely, it is some "brittle base class" situation that I haven't considered...


Why do you need such feature? It is not possible to prevent neither properties not methods from hiding in subclasses.


What about adding the ancestor to DomainObject where the IsDeleted would be marked virtual and afterwards in DomainObject you would be able to mark it sealed override?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜