C# GetMethod的正确参数类型
在下面的代码中,我应该如何设置变量“paramType”,使其与GetMethod()调用中显示的方法相匹配 下面的代码与示例类中的方法不匹配(methodInfo为null) 这也不起作用-此不同版本的C# GetMethod的正确参数类型,c#,reflection,C#,Reflection,在下面的代码中,我应该如何设置变量“paramType”,使其与GetMethod()调用中显示的方法相匹配 下面的代码与示例类中的方法不匹配(methodInfo为null) 这也不起作用-此不同版本的paramType与更多信息似乎不匹配 在非一般情况下,有人可能希望像这样调用“MyMethod”: // I want to use a MethodInfo to perform this function: new MyClass<Program>().MyMethod( _p
paramType
与更多信息似乎不匹配
在非一般情况下,有人可能希望像这样调用“MyMethod”:
// I want to use a MethodInfo to perform this function:
new MyClass<Program>().MyMethod( _program => _program.MyProperty );
//我想使用MethodInfo执行此函数:
新建MyClass().MyMethod(\u program=>\u program.MyProperty);
要做到这一点,您需要知道泛型类型,否则我认为您的任务不可能完成
如果您的意图是在泛型类知道其任何类型之前为泛型类创建泛型methodinfo,以便以后可以使用两个类型调用MakeGenericType
,那么这是不可能的
这可以通过调用typeof(MyClass).GetMethod(“MyMethod”)
来显示,它将返回null
另一方面,如果您知道具体的类型,这很容易:
static MethodInfo GetMethod(Type classType, Type methodType)
{
var genericClassType = typeof(MyClass<>).MakeGenericType(classType);
var methodInfo = genericClassType.GetMethod("MyMethod");
var genericMethodInfo = methodInfo.MakeGenericMethod(methodType);
return genericMethodInfo;
}
static MethodInfo GetMethod(类型classType,类型methodType)
{
var genericClassType=typeof(MyClass)。MakeGenericType(classType);
var methodInfo=genericClassType.GetMethod(“MyMethod”);
var genericMethodInfo=methodInfo.MakeGenericMethod(methodType);
返回genericMethodInfo;
}
请注意,我没有为表达式
参数创建泛型类型
当您创建genericClassType
并对其调用GetMethod
时,CLR还不知道TMethod
将是什么类型。只有在调用methodInfo
上的MakeGenericType
时才知道这一点。因此,如果使用完全参数化的表达式
类型调用GetMethod
,它将找不到该方法
这就是为什么需要调用
genericClassType.GetMethod(“MyMethod”)
而不使用参数类型,并且如果方法重载,可能需要对其进行过滤。之后,您可以调用MakeGenericMethod(methodType)
并将您的methodInfo对象完全参数化。我相信您的问题的答案是,“没有办法做到这一点”
由于GetMethod在执行查找时无法“MakeGenericMethod”,因此您有一个方法,其中一个泛型参数已知(TClass),另一个未知(TMethod)。当某些(但不是全部)参数已知时,反射无法查找方法
注意-即使您知道TMethod应该是什么(“在您的示例中是int”),这也需要我在上一段中提到的“MakeGenericMethod” 谢谢你的参考资料,但这两个都不能回答我的具体问题。一个答案似乎涉及到遍历一个类型的成员,而另一个答案没有将一个泛型类型嵌套在另一个泛型类型中。我将以更多的背景再次编辑该问题。更具体地说,没有类型参数的
GetMethod
将是不明确的,这就是我首先需要类型参数的原因。对于泛型方法,您将无法使用调用GetMethod,因为其参数取决于泛型方法类型(这就是您正在尝试做的)。在对泛型方法调用MakeGenericMethod之前,CLR无法知道该泛型方法将具有哪种类型。因此,您需要在不使用参数的情况下调用GetMethod,并且需要在必要时遍历所有找到的方法。遗憾的是,没有更好的方法,您无法创建具有反射的泛型类型,类型参数的作用在哪里s还没有确定。我认为情况也是如此——我找不到更好的答案。
// I want to use a MethodInfo to perform this function:
new MyClass<Program>().MyMethod( _program => _program.MyProperty );
static MethodInfo GetMethod(Type classType, Type methodType)
{
var genericClassType = typeof(MyClass<>).MakeGenericType(classType);
var methodInfo = genericClassType.GetMethod("MyMethod");
var genericMethodInfo = methodInfo.MakeGenericMethod(methodType);
return genericMethodInfo;
}