C#CA2104-自动代码分析不喜欢静态只读可变类型 [英] C# CA2104 - Automated Code Analysis dislikes static readonly mutable types

查看:73
本文介绍了C#CA2104-自动代码分析不喜欢静态只读可变类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

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();
}

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

Visual Studio 2008's Code Analysis pops up this message:


CA2104:Microsoft.Security:从 Base.StaticFoo中删除只读名称,或将字段更改为不可变的参考类型。如果引用类型'Foo'实际上是不可变的,则排除此消息。

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

Is my design instrinsically flawed, or can i add a [SuppressMessage] in the source?

推荐答案

问题在于它给人留下了错误的印象-它看起来值似乎无法更改,而实际上只是 field 值无法更改,而不是对象。我认为这里的代码分析过于谨慎-在很多地方,您可能希望将可变类型存储在只读字段中,特别是如果它是私有的,则在静态初始化程序中进行初始化,然后再在代码内进行更改。

The problem is that it gives the wrong impression - it makes it look like the value can't change, when actually it's only the field value that can't change, rather than the object. I think the code analysis is being overly cautious here - there are plenty of places where you might want a mutable type stored in a readonly field, particularly if it's private, initialized in a static initializer and then never mutated within your code.

尽管该字段受到保护,但派生类滥用该字段的风险更大。就我个人而言,我希望所有领域都是私有的。另一方面,我不知道您的代码-可能是您权衡了可能性,并认为这是正确的做法。

While the field is protected, however, there's more of a risk of derived classes abusing it. Personally I like all my fields to be private. On the other hand, I don't know your code - it could be that you've weighed that up against the possibilities and decided it's the right thing to do.

如果 Foo 确实是线程安全的,则不必担心,除了该字段为只读的事实给人的不变性的印象外。我会禁用该行的警告,并添加一条注释以强调即使该字段是只读的,该对象也是可变的。

If Foo really is thread-safe, there's less to worry about, other than the general impression of immutability given by the fact that the field is readonly. I'd disable the warning for that line, and add a comment to emphasize that the object is mutable even though the field is readonly.

这篇关于C#CA2104-自动代码分析不喜欢静态只读可变类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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