开发者

Execute method with Action<T> argument using Reflection

开发者 https://www.devze.com 2022-12-25 14:18 出处:网络
How can i create a Action method to use as a argument to the following function? public void When(Action<T&开发者_如何学Pythongt; action)

How can i create a Action method to use as a argument to the following function?

public void When(Action<T&开发者_如何学Pythongt; action) 
{
    if (internalValue != null)
        action(internalValue);
}

I have the MethodInfo on the method, and the parameter type like so:

var methods = value.GetType().GetMethods();
MethodInfo mInfo = methods.First(method => method.Name == "When");
Type parameterType = (mInfo.GetParameters()[0]).ParameterType;

But after that i have no idea how to make the actual Action method to pass as argument, i also do not know how to define the Action method body.


mInfo.Invoke(value,
    delegate(<TheRuntimeTypeOf T> aTinstance)
    {
        // do something on a T
    });

But keep in mind that you're loosing the genericity.

0

精彩评论

暂无评论...
验证码 换一张
取 消