lundi 22 novembre 2021

Define a generic lambda in C# and assign it to a variable to be used with MakeGenericMethod

I know I can define a generic function and then call it with Type parameters by help of reflection. Something like that:

private static void SomeFunc<Tf>()
{
    // Something type safe against Tf
}

public void CallingFunc()
{
    var someType = typeof(whatever); // This may be retrieved using reflection as well instead
    var someMethod = this.GetType().GetMethod(nameof(SomeFunc)), BindingFlags.Static | BindingFlags.NonPublic);
    var typedMethod = someMethod.MakeGenericMethod(someType);
    typedMethod.Invoke(null, null);
}

Now, is there a way to declare this SomeMethod<Td>() inline as a lambda, to avoid declaring it as a separate method in the class, but still being able to use it with MakeGenericMethod? Something like:

public void CallingFunc()
{
    var someType = typeof(whatever); // This may be retrieved using reflection as well instead

    // This obviously doesn't work as it requires Tf to be known at this stage, and we can have Tf only as a Type variable here => what should I do instead?
    var someMethod = new Action<Tf>(() => /* Something type safe against Tf */).Method;

    var typedMethod = someMethod.MakeGenericMethod(someType);
    typedMethod.Invoke(null, null);
}

Making CallingFunc generic as well is not an option - the someType variable is retrieved with reflection so is not known on compile time.





Aucun commentaire:

Enregistrer un commentaire