如何获取泛型方法的类型参数?

时间:2012-07-25 12:56:08

标签: c# generics delegates

假设我有这个通用方法

void ActivateView<T>(ViewCommand command) where T : IPresenter
{
    //code
}

我的行动是:

Action<ViewCommand> action = this.ActivateView<DiagnosticPresenter>;

现在给定action,我怎么知道泛型方法ActivateView的类型arument?在这种情况下,它应该是DiagnosticPresenter。所以我期待Type的实例等于typeof(DiagnosticPresenter)

Type type = Magic(action); //what should Magic do?
if ( type == typeof(DiagnosticPresenter))
{
    //I want to do something here!
}

这可能吗?我该如何实施Magic()

1 个答案:

答案 0 :(得分:3)

这似乎对我有用:

public Type Magic(Action action)
{
    return action.Method.GetGenericArguments().First();
}