相关疑难解决方法(0)

如何使用反射来调用泛型方法?

当在编译时未知类型参数但是在运行时动态获取时,调用泛型方法的最佳方法是什么?

考虑以下示例代码 - 在Example()方法内部,GenericMethod<T>()使用Type存储在myType变量中调用的最简洁方法是什么?

public class Sample
{
    public void Example(string typeName)
    {
        Type myType = FindType(typeName);

        // What goes here to call GenericMethod<T>()?
        GenericMethod<myType>(); // This doesn't work

        // What changes to call StaticMethod<T>()?
        Sample.StaticMethod<myType>(); // This also doesn't work
    }

    public void GenericMethod<T>()
    {
        // ...
    }

    public static void StaticMethod<T>()
    {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

c# generics reflection

1002
推荐指数
6
解决办法
24万
查看次数

GetMethod用于泛型方法

我正在尝试为Enumerable类型的Where方法检索MethodInfo:

typeof (Enumerable).GetMethod("Where", new Type[] { 
     typeof(IEnumerable<>), 
     typeof(Func<,>) 
})
Run Code Online (Sandbox Code Playgroud)

但得到null.我究竟做错了什么?

.net c# reflection

47
推荐指数
2
解决办法
3万
查看次数

选择具有反射的右通用方法

我想通过反射选择正确的通用方法,然后调用它.

通常这很容易.例如

var method = typeof(MyType).GetMethod("TheMethod");
var typedMethod = method.MakeGenericMethod(theTypeToInstantiate);
Run Code Online (Sandbox Code Playgroud)

但是,当方法存在不同的泛型重载时,问题就开始了.例如,System.Linq.Queryable类中的静态方法.'Where'方法有两种定义

static IQueryable<T> Where(this IQueryable<T> source, Expression<Func<T,bool>> predicate)
static IQueryable<T> Where(this IQueryable<T> source, Expression<Func<T,int,bool>> predicate)
Run Code Online (Sandbox Code Playgroud)

这说明GetMethod无法正常工作,因为它无法让两者黯然失色.因此,我想选择正确的.

到目前为止,我经常只采取第一种或第二种方法,这取决于我的需要.像这样:

var method = typeof (Queryable).GetMethods().First(m => m.Name == "Where");
var typedMethod = method.MakeGenericMethod(theTypeToInstantiate);
Run Code Online (Sandbox Code Playgroud)

但是我对此并不满意,因为我做了一个很大的假设,即第一种方法是正确的.我宁愿通过参数类型找到正确的方法.但我无法弄清楚如何.

我尝试传递'类型',但它没有用.

        var method = typeof (Queryable).GetMethod(
            "Where", BindingFlags.Static,
            null,
            new Type[] {typeof (IQueryable<T>), typeof (Expression<Func<T, bool>>)},
            null);
Run Code Online (Sandbox Code Playgroud)

所以有人知道如何通过反射找到'正确'的通用方法.例如,Queryable类的'Where'方法的正确版本?

c# reflection

34
推荐指数
4
解决办法
1万
查看次数

标签 统计

c# ×3

reflection ×3

.net ×1

generics ×1