简体   繁体   中英

c# dictionary method as a value

I have a class with a bunch of methods in it, the methods transfer variables elsewhere in my program when called. I want to use a dictionary as the middle man between the methods that transfer data and the methods that call them.

So here is my question. Say I make a dictionary, where the key is an int and I want the value to be the name of a method. I will assign a new value / method each time I add to the dictionary. Is there a value type I can put there that will let me do this?

Dictionary<int, ?> methodKey= new Dictionary<int, ?>();

I tried to find a list of types that dictionary will take but I couldn't find anything specific.

Thanks in advance

Use any delegate type as a type of value. For example:

Dictionary<int, Action>

So, you'll be able to write such things:

        dictionary[0] = () => Console.WriteLine("0");
        dictionary[1] = Foo;
        dictionary[2] = a.Bar;

Specific delegate type depends on your needs - may be, you want for methods to have some input parameters or output/return values, but it should be most common type.

Will all the methods have the same signature? If so you can probably use one of the existing Action or Func delegate, (or you can create a delegate type with that signature), and use that as your second type parameter.

If not, you can use Delegate (or even object ) and cast to the appropriate type when you invoke the delegates.

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