How to fix "CA1810: initialize static fields of reference type inline" with abstract base ...?

Here are the simplified parts of the code that I have:

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

and then I:

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

And now I get CA1810. I see several solutions, such as creating Valuespublic and setting them up elsewhere, but I don’t like it, or make a static method in TextManagerto do the same, but it is called when the program starts, but I also don’t like it.

I think the example shows that it Valuesshould be filled only once per TValue. So, what do you think is the best solution here?

+3
source share
2 answers

. , , (AFAIK) . , , inline ( MSDN). inline, :

  • , , TextManager.

, , ( ", Microsoft. , , , " ).

MSDN : " , , , , ."

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

(: Mono 2.6.7, .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());    
}
+3

- , . , , .

0

Source: https://habr.com/ru/post/1794107/


All Articles