Question

I'm dynamically creating a type from a string passed to me at runtime.

I have the following code at the moment:

string messageType = "CustomerCreatedMessage";
//Convert the string to a Type
var type = Type.GetType(messageType);
//Create a Type of Action<CustomerCreatedMessage>
var action = typeof(Action<>).MakeGenericType(messageType);

How would I make a variable of the type of action and assign the lambda m=> SetActive(true) to it? I will then use the variable (named ??? here) in the following code:

//Create a generic method "Register" on my Messenger class that takes an Action<CustomerCreatedMessage> parameter.
var method = typeof(Messenger).GetMethod("Register");
var genericMethod = method.MakeGenericMethod(action);
//Invoke the created method with our script in it
genericMethod.Invoke(Messenger.Default, ???);

My goal is to be able to call my generic method Messenger.Default.Register<> with an Action<> that takes as type parameter a type created from my messageType string.

I have tried the following already:

Convert.ChangeType(m=>SetActive(true),action);

var filledAction = Activator.CreateInstance(action);
filledAction = m=>SetActive(true);

But both methods complain about converting a lambda expression to an object because it is not a delegate.

I get a similar error if I put SetActive(true) into a method and try to pass the method group.

Was it helpful?

Solution

Given that you're not using the parameter at all, I'd create a new generic method:

private static void GenericSetActive<T>(T ignored)
{
    SetActive(true);
}

Then create a delegate using that:

var genericMethod = typeof(Foo).GetMethod("GenericSetActive",
                                          BindingFlags.NonPublic |
                                          BindingFlags.Static);
var concreteMethod = genericMethod.MakeGenericMethod(type);
var actionInstance = Delegate.CreateDelegate(action, concreteMethod);

Basically, you can't use a lambda expression here because you don't have a specific delegate type to convert it to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top