简体   繁体   中英

C# Anonymous collection initializer for a method dictionary

Trying to make a dictionary that stores methods, those methods create stuff in windows forms, etc.

The method takes no parameters and returns Dictionary of all the items created.

Dictionary<string, Func<Dictionary<string, dynamic>>> games = new 
Dictionary<string, Func<Dictionary<string, dynamic>>>()
{
    { "Buttoncatch", //I dont know what to write here
        {
           var objects = new Dictionary<string, dynamic>
           return objects;
        }
    }
};

I do not want to do this:

public Dictionary<string, dynamic> Buttoncatch()
{

}
games["Buttoncatch"] = Buttoncatch //dont even know what to write here, 
problems of self teaching

Why is the value type of your dictionary dynamic , it can be Func<Dictionary<string,dynamic>> .

And the methods can be created as normal lambdas:

Dictionary<string, Func<Dictionary<string,dynamic>>> games = new     
Dictionary<string, Func<Dictionary<string, dynamic>>>
{
   {"Buttoncatch", 
    () => {
             var objects = new Dictionary<string, dynamic>
             return objects;
          }
   }
};

And when you declare the dictionary that way, the line

games["Buttoncatch"] = Buttoncatch;

will work, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM