Code Analysis Warning 2214 - How best to fix?

前端 未结 1 848
醉话见心
醉话见心 2021-01-05 02:41

I have the following code:

    public partial class AuditLog : IBusinessEntity
    {
        public BusinessEntityType EntityType { get { return BusinessEnti         


        
相关标签:
1条回答
  • 2021-01-05 03:13

    Is one or more of your properties virtual ? Then that is why, since CA2214 is the "Do not call overridable methods in constructors" warning.

    Here is the reasoning for the rule from MSDN:

    When a virtual method is called, the actual type that executes the method is not selected until run time. When a constructor calls a virtual method, it is possible that the constructor for the instance that invokes the method has not executed.

    What this means is that if someone inherits from your class, and overrides a method or property that is accessed in your constructor - then the overriding implementation will be hit before the constructor for the inherited class has run. This might lead to problems if the overriding implementation relies on state set in the constructor.

    To satisfy the warning, you need to make the properties and methods accessed in the constructor non-virtual (you could make the type sealed, if appropiate).

    0 讨论(0)
提交回复
热议问题