Wahooney
Wahooney

Reputation: 23

How do I make a generic delegate using a type in C#?

If I have a type, like:

Type type = myObject.GetType ();

How do I make a generic delegate that uses objects of that that type as a parameter? I would expect code something like:

myDelegate = Action<type> (type parameter);

The above code obviously won't and doesn't work as is, but how can I make it work? Can I even make it work?

Ultimately, I have a dictionary of Dictionary < Type, List < Action < > >, which holds a type and a list of delegates that should take an object of that type as parameter.

And should be executed something like this:

myDict[myType][i] (objectOfMyType);

Any suggestions would be greatly appreciated.

Thanks!

Upvotes: 2

Views: 1927

Answers (1)

thecoop
thecoop

Reputation: 46098

As you might expect, you can't use instantiations of the Action<> type directly in the dictionary. You'll have to type it to System.Delegate, and use DynamicInvoke:

Dictionary<Type, List<Delegate>> dict;

dict[myType][i].DynamicInvoke(objectOfMyType);

and to create the delegates in the first place, use reflection:

Type delegateType = typeof(Action<>).MakeGenericType(myType);

MethodInfo delegatedMethod = typeof(ContainingType).GetMethod("MethodToInvoke");

Delegate myDelegate = Delegate.CreateDelegate(delegateType, delegatedMethod);
dict.Add(myType, new List<Delegate> {myDelegate});

Upvotes: 2

Related Questions