gpt4 book ai didi

c# - 代码分析警告 2214 - 如何最好地修复?

转载 作者:太空狗 更新时间:2023-10-29 18:19:20 25 4
gpt4 key购买 nike

我有以下代码:

    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 警告。 BusinessEntityTypeAuditLogCommand 方法参数都是枚举。我看不出这里有什么问题,因此不确定如何满足警告。

谢谢。

最佳答案

您的一个或多个属性是虚拟的吗?那就是为什么,因为CA2214 is the "Do not call overridable methods in constructors"警告。

这是来自 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.

的意思是,如果有人继承了你的类,并覆盖了在你的构造函数中访问的方法或属性——那么覆盖的实现将在之前被命中继承类的构造函数已运行。如果覆盖实现依赖于构造函数中设置的状态,这可能会导致问题。

为了满足警告,您需要使在构造函数中访问的属性和方法成为非虚拟的(如果合适,您可以将类型设置为密封的)。

关于c# - 代码分析警告 2214 - 如何最好地修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3963219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com