简体   繁体   English

C#继承最佳实践

[英]C# Inheritance best-practice

I have a normal class called BaseView with a virtual method DisplayView . 我有一个名为BaseView的普通类,它带有一个虚方法DisplayView This method calls GetHeader and GetBody virtual methods to get contents for the page. 此方法调用GetHeaderGetBody虚拟方法来获取页面的内容。 I would then create a class that inherits from BaseView and override the methods that needs to display content differently than the way the base class does it. 然后,我将创建一个继承自BaseView的类,并覆盖需要以与基类的方式不同的方式显示内容的方法。

My issue is that, although this works great, when running a code analysis I'm warned not to call the virtual functions directly. 我的问题是,尽管这很有效,但在运行代码分析时,我警告不要直接调用虚函数。

Should I create another class layer on top of the base class that override the virtual functions and only inherit from that? 我应该在基类之上创建另一个类层来覆盖虚函数并且只继承它吗?

What are the disadvantages of using the virtual methods directly? 直接使用虚方法有哪些缺点?

EDIT: the warning is: 编辑:警告是:

CA2214 : Microsoft.Usage : xxx contains a call chain that results in a call to a virtual method defined by the class. CA2214:Microsoft.Usage:xxx包含一个调用链,该调用链导致调用该类定义的虚方法。 Review the following call stack for unintended consequences 检查以下调用堆栈是否存在意外后果

I think the issue is that DisplayView is virtual, and it's calling virtual methods. 我认为问题是DisplayView是虚拟的,它正在调用虚拟方法。 In most cases virtual methods are called by final methods as a means of changing behaviour, for example in the strategy pattern. 在大多数情况下,最终方法调用虚方法作为改变行为的手段,例如在策略模式中。 If a final method calls a virtual method, the compiler knows that the virtual method will always be called in all deriving classes, and therefore it is valid for the virtual method to exist. 如果final方法调用虚方法,则编译器知道将始终在所有派生类中调用虚方法,因此它对于存在的虚方法是有效的。

The fact that you're calling virtual from virtual means that your design can be called into question: if DisplayView is virtual, another implementation may override it. 您从虚拟调用虚拟的事实意味着您的设计可能会受到质疑:如果DisplayView是虚拟的,则另一个实现可能会覆盖它。 The current implementation calls the virtual GetHeader but a deriving class may not. 当前实现调用虚拟GetHeader但派生类可能不调用。 Therefore it cannot guarantee that GetHeader is not dead code. 因此,它不能保证GetHeader不是死代码。

This is probably what FxCop is drawing your attention to. 这可能是FxCop引起你注意的。 It wants to know that if you define a virtual method ( GetHeader in this case) in a base class that all deriving implementations will use it. 它想知道如果在基类中定义一个虚方法(在本例中为GetHeader ),所有派生实现都将使用它。

I would focus on making DisplayView final, or appraise your design in that light. 我将专注于制作DisplayView ,或者从那个角度评估您的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM