代码分析警告2214 - 如何以最佳方式解决? [英] Code Analysis Warning 2214 - How best to fix?

查看:158
本文介绍了代码分析警告2214 - 如何以最佳方式解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

    public partial class AuditLog : IBusinessEntity
    {
        public BusinessEntityType EntityType { get { return BusinessEntityType.AuditLog; } }

        /// <summary>
        /// Constructor accepting parameter initialization arguments
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="entity"></param>
        /// <param name="command"></param>
        /// <param name="commandText"></param>
        public AuditLog(string userName, BusinessEntityType entity, AuditLogCommand command, string commandText)
        {
            this.Timestamp = DateTime.Now;
            this.UserName = userName;
            this.Entity = entity.ToString();
            this.Command = command.ToString();
            this.CommandText = commandText;
        }
    }

这是生成CA2214警告。在 BusinessEntityType AuditLogCommand 方法的参数都是枚举。我没有看到的问题是什么在这里,所以我不能确定如何满足警告。

This is generating a CA2214 warning. The BusinessEntityType and AuditLogCommand method parameters are both enumerations. I don't see what the issue is here, and therefore am not certain how to satisfy the warning.

感谢。

推荐答案

是一个或多个属性的虚拟?那么这就是为什么,因为 CA2214是不要叫重写的方法构造函数警告。

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

下面是从MSDN规则的理由:

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).

这篇关于代码分析警告2214 - 如何以最佳方式解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆