C#CA2104 - 自动代码分析不喜欢静态只读可变类型

maf*_*afu 4 c# code-analysis visual-studio-2008

我有这样的代码:

public abstract class Base
{
    // is going to be used in deriving classes
    // let's assume foo is threadsafe
    protected static readonly Foo StaticFoo = new Foo();
}
Run Code Online (Sandbox Code Playgroud)

Visual Studio 2008的代码分析弹出以下消息:

CA2104 : Microsoft.Security : Remove the read-only designation from 'Base.StaticFoo' or change the field to one that is an immutable reference type. If the reference type 'Foo' is, in fact, immutable, exclude this message.

我的设计是否存在本质上的缺陷,或者我可以[SuppressMessage]在源代码中添加一个?

Jon*_*eet 8

问题在于它给出了错误的印象 - 它使得它看起来像值不能改变,而实际上它只是不能改变的字段值,而不是对象.我认为代码分析在这里过于谨慎 - 有很多地方你可能想要一个存储在只读字段中的可变类型,特别是如果它是私有的,在静态初始化程序中初始化然后从不在代码中变异.

虽然该字段受到保护,但派生类滥用它的风险更大.我个人认为我的所有领域都是私人的.另一方面,我不知道你的代码 - 可能是你已经权衡了可能性,并认为这是正确的做法.

如果Foo真的是线程安全的话,那么除了由于该字段是只读的事实给出的不可变性的一般印象之外,不用担心.我将禁用该行的警告,并添加注释以强调该对象是可变的,即使该字段是只读的.