开发者

How to 'GetMethod' on multiple function definitions where match has generic parameter type?

I need to invoke a method on a class using reflection. The class contains two overloads for the same function:

    string GenerateOutput<TModel>(TModel model);
    string GenerateOutput开发者_StackOverflow<TModel>(TModel model, string templateName);

I'm getting the method like so:

    Type type = typeof(MySolution.MyType);
    MethodInfo method = typeof(MyClass).GetMethod("GenerateOutput", new Type[] {type ,typeof(string)});
    MethodInfo generic = method.MakeGenericMethod(type);

The method is not fetched (method = null), I guess because the first method parameter is a generic type. How should this be handled?


There are two possible issues - finding a method if it is non-public (the example shows non-public), and handling the generics.

IMO, this is the easiest option here:

MethodInfo generic = typeof(MyClass).GetMethods(
        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
    .Single(x => x.Name == "GenerateOutput" && x.GetParameters().Length == 2)
    .MakeGenericMethod(type);

You could make the Single clause more restrictive if it is ambiguous.


In .NET, when working with generics and reflection, you need to provide how many generic parameters has a class or method like so:

"NameOfMember`N" 

Where "N" is generic parameters' count.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜