在下面的代码中,我应该如何设置变量"paramType“,使其与GetMethod()调用中显示的方法相匹配?
下面的代码与示例类中的方法不匹配(methodInfo为null)。
using System;
using System.Linq.Expressions;
public class MyClass<TClass>
{
public void MyMethod<TMethod>( Expression<Func<TClass, TMethod>> expr )
{
}
}
class Program
{
static void Main( string[] args )
{
var classType = typeof( MyClass<> );
// What should this really be?
var paramType = typeof( Expression<> ).MakeGenericType( typeof( Func<,> ) );
var methodInfo = classType.GetMethod( "MyMethod", new Type[] { paramType } );
}
}编辑:我知道如何使用MethodInfo或其他形式的迭代/假设获得GetMethods。我的问题是如何设置System.Type of paramType,如果可以为它生成一个System.Type的话。
编辑2:为了更具体地处理这个问题,我更新了代码,使其更具趣味性:
using System;
using System.Linq.Expressions;
public class MyClass<TClass>
{
public void MyMethod<TMethod>( Expression<Func<TClass, TMethod>> expr )
{
Console.WriteLine( "Type: {0} Return: {1}", typeof( TClass ).Name, typeof( TMethod ).Name );
}
public void MyMethod<TMethod>( TMethod param )
{
}
}
class Program
{
public int MyProperty { get; set; }
static void Main( string[] args )
{
var classType = typeof( MyClass<> );
var typeClass = typeof( Program );
var typeMethod = typeof( int );
// What should this really be?
var paramType = typeof( Expression<> )
.MakeGenericType( typeof( Func<,> )
.MakeGenericType( typeClass, typeMethod )
);
var methodInfo = classType
.MakeGenericType( typeClass )
.GetMethod( "MyMethod", new Type[] { paramType } );
}
}这也不起作用--这个包含更多信息的不同版本的paramType似乎不匹配。
在非一般情况下,有人可能想这样称呼"MyMethod“:
// I want to use a MethodInfo to perform this function:
new MyClass<Program>().MyMethod( _program => _program.MyProperty );发布于 2015-05-30 14:03:27
我相信你的问题的答案是,“没有办法做到这一点”。
因为GetMethod在进行查找时不能"MakeGenericMethod“,所以您有一个方法,它有一个已知的泛型参数(TClass)和一个不知道的(TMethod)。当已知一些参数(但不是全部参数)时,反射无法查找方法。
注意:尽管do知道TMethod应该是什么(在示例中是“int”),但这需要我在上一段中引用的"MakeGenericMethod“。
发布于 2015-05-29 22:43:41
要做到这一点,您需要知道泛型类型,否则我认为您的任务是不可能的。
如果您的目的是为泛型类创建泛型方法信息,那么在它还不知道它的任何类型之前,您以后就可以调用带有两种类型的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;
}注意,我没有为Expression<Func<TClass,TMethod>>参数创建泛型类型。
当您创建genericClassType并在其上调用GetMethod时,CLR还不知道TMethod的类型。只有当您在MakeGenericType上调用methodInfo时,才会知道这一点。因此,如果要使用完全参数化的GetMethod类型调用Expression<Func<TClass,TMethod>>,则不会找到该方法。
这就是为什么您需要调用没有参数类型的genericClassType.GetMethod("MyMethod"),并且在方法重载的情况下可能需要对其进行筛选。之后,您可以调用MakeGenericMethod(methodType)并拥有完全参数化的methodInfo对象。
https://stackoverflow.com/questions/30539611
复制相似问题