How to fix “CA1810: Initialize reference type static fields inline” with an abstract base…?

风流意气都作罢 提交于 2020-06-27 08:56:33

问题


Here's the simplified parts of code that I have:

abstract class DataManager<TValue>
{
    protected static Dictionary<string, TValue> Values;
}

and then I have:

class TextManager : DataManager<string>
{
    static TextManager()
    {
        Values = ... // Fill with data
    }
}

And, now I'm getting CA1810. I see a few solutions, like making Values public and setting them elsewhere, but I don't like that, or making a static method in TextManager to do the same thing, but is invoked when the program starts, but I don't like that either.

I think it's obvious from the example, the Values should only be filled once per TValue. So, what do you think would be the best solution here?


回答1:


I would turn off the rule. The thing is, you have a rule that (AFAIK) is designed to warn you about the potential performance hit of using a static constructor. I would say that initialization of a static property can be done either via a static constructor or inline (as suggested by MSDN). In your case you can't do it inline because:

  1. you only have the actual values in the subclass
  2. there's no such thing as an abstract static method, so you can't delegate the actual inline initialization to TextManager.

So that leaves the static constructor option, which basically means turning off the rule (which means "yes, Microsoft. I know this might be dangerous for performance, but I know what I'm doing").

MSDN states: "It is safe to suppress a warning from this rule if performance is not a concern; or if global state changes that are caused by static initialization are expensive or must be guaranteed to occur before a static method of the type is called or an instance of the type is created."

=======================================================================

Try this (warning: tested on Mono 2.6.7, not .NET):

abstract class DataManager<TValue>
{
    protected static Dictionary<string, TValue> Values=new Dictionary<string, TValue>();
}

class TextManager : DataManager<string>
{
    static TextManager()
    {
        Values.Add("test","test");
    }

    public static string test()
    {
        return Values["test"];
    }
}

class IntManager : DataManager<int>
{
    static IntManager()
    {
        Values.Add("test",1);
    }

    public static int test()
    {
        return Values["test"];
    }   
}

public static void Main (string[] args)
{
    Console.WriteLine(IntManager.test());    
    Console.WriteLine(TextManager.test());    
}



回答2:


Code analysis warnings are just that, warnings intended to flag potential issues. If you have a good reason to do what you do, then do it.



来源:https://stackoverflow.com/questions/5090076/how-to-fix-ca1810-initialize-reference-type-static-fields-inline-with-an-abst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!