使用Reflection </t>使用Action <t>参数执行方法

时间:2010-04-01 09:26:38

标签: c# reflection

如何创建一个Action方法作为以下函数的参数?

public void When(Action<T> action) 
{
    if (internalValue != null)
        action(internalValue);
}

我在方法上有MethodInfo,参数类型如下:

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

但之后我不知道如何将实际的Action方法作为参数传递,我也不知道如何定义Action方法体。

1 个答案:

答案 0 :(得分:2)

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

但请记住,你正在失去普遍性。