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<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?
我没有获取该方法(method = null),因为第一个方法参数是泛型类型。应如何处理?
2 个解决方案
#1
4
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:
IMO,这是最简单的选择:
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.
如果不明确,您可以使Single子句更具限制性。
#2
1
In .NET, when working with generics and reflection, you need to provide how many generic parameters has a class or method like so:
在.NET中,当使用泛型和反射时,您需要提供有多少通用参数的类或方法,如下所示:
"NameOfMember`N"
Where "N" is generic parameters' count.
其中“N”是通用参数的计数。
#1
4
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:
IMO,这是最简单的选择:
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.
如果不明确,您可以使Single子句更具限制性。
#2
1
In .NET, when working with generics and reflection, you need to provide how many generic parameters has a class or method like so:
在.NET中,当使用泛型和反射时,您需要提供有多少通用参数的类或方法,如下所示:
"NameOfMember`N"
Where "N" is generic parameters' count.
其中“N”是通用参数的计数。