C # compiler and caching of local variables

EDIT: . Unfortunately, there was no way to find out whether the constructor for the class in question is sensitive to when or how many times it is called, or if the state of the object changes during the method, so it will need to be created from scratch every time. Ignore the dictionary and just think that delegates are created in line mode during the method :-)


Let's say I have the following method with the local variable Dictionary of Type to Action.

void TakeAction(Type type)
{
    // Random types chosen for example.
    var actions = new Dictionary<Type, Action>()
    {
        {typeof(StringBuilder), () =>
            {
                // ..
            }},
         {typeof(DateTime), () =>
            {
                // ..
            }}
    };

    actions[type].Invoke();
}

. # , - ? ? , , , , , .

+3
4

# , " " ? . # , . , .

, # . , ?:)

+7

: .

: , , ( "this"), .

: readonly .

private static readonly Dictionary<Type,Action> Actions = 
    new Dictionary<Type, Action>()
{
    { typeof(StringBuilder), () => ... },
    { typeof(DateTime), () => ... },
}

void TakeAction(Type type)
{
    Actions[type].Invoke();
}
+7

, - :

  • , . , , , , , , Random typ.e
  • . , . , , .

, , , , .

# .NET , , - , , . , , , .

, , , , , , , .

+2

This dictionary will be recreated every time; otherwise, for example, you could put other words in the dictionary and the intention would be lost.

+1
source

All Articles