IQueryable OfType <T>其中T是运行时类型

Tab*_*let 25 c# linq reflection iqueryable

我需要能够得到类似以下的东西才能工作:

Type type = ??? // something decided at runtime with .GetType or typeof;
object[] entityList = context.Resources.OfType<type>().ToList();
Run Code Online (Sandbox Code Playgroud)

这可能吗?如果有任何新内容允许,我可以使用.NET 4.

Jon*_*eet 39

你可以通过反思来调用它:

MethodInfo method = typeof(Queryable).GetMethod("OfType");
MethodInfo generic = method.MakeGenericMethod(new Type[]{ type });
// Use .NET 4 covariance
var result = (IEnumerable<object>) generic.Invoke
      (null, new object[] { context.Resources });
object[] array = result.ToArray();
Run Code Online (Sandbox Code Playgroud)

另一种方法是编写自己的OfTypeAndToArray泛型方法来完成它的两个位,但上面的方法应该可行.


Tim*_*mwi 8

看起来你需要在这里使用Reflection ...

public static IEnumerable<object> DyamicOfType<T>(
        this IQueryable<T> input, Type type)
{
    var ofType = typeof(Queryable).GetMethod("OfType",
                     BindingFlags.Static | BindingFlags.Public);
    var ofTypeT = ofType.MakeGenericMethod(type);
    return (IEnumerable<object>) ofTypeT.Invoke(null, new object[] { input });
}

Type type = // ...;
var entityList = context.Resources.DynamicOfType(type).ToList();
Run Code Online (Sandbox Code Playgroud)