3

我有一种从数据库中获取数据的方法,它是通用的:

public static IQueryable<T> GetData<T>(IQueryable<T> data, some more parameters)

data 是未过滤的数据库实体集合,GetData 进行过滤、排序、跳过、处理该集合......

当我像通常那样提供 IQueryable 类型的变量(例如,T 是 Document)作为第一个参数时,它当然可以工作:

IQueryable<Document> data = ... 
GetData<Document>(data, ....);

现在,我需要动态地“计算”第一个参数。为此,我使用 LINQ 表达式,它将评估为 IQueryable,但在编译时我不知道哪个 T。我在想这样的事情:

Expression db = Expression.Constant(new DataModelContainer());
Expression table = Expression.Property(db, tbl); /* tbl = "Documents", this is the whole point */ 
Type type = table.Type.GetGenericArguments()[0];
Expression call = Expression.Call(typeof(Queryable), "AsQueryable", new Type[] { type }, table);            
object o = Expression.Lambda(call, null).Compile().DynamicInvoke();

此时 o INDEED IS IQueryable (IQueryable),因此应该能够作为 GetData 的参数。但是,我只有对它的“对象”引用,自然不能那样使用它。

所以,我的问题是:当 o 正好是这样时,有没有办法将 'o' 动态转换为 'IQueryable'。我知道演员表是编译时的事情,但我希望有人有某种解决方法。或者,也许我正在尝试太多。

4

2 回答 2

4

您可以使用该dynamic功能。动态非常适合您已经必须进行反射的情况:

dynamic o = Expressin.Lambda(...
于 2013-02-23T20:33:00.807 回答
1

得到这个家伙的负载:

第一的。我们假设围绕您的GetData < T >方法的类称为Foo

public static class Foo {

    public static IQueryable<T> GetData<T>(IQueryable<T> data, int bar, bool bravo) {
        // ... whatever
    }

然后我们尝试反思GetData < >的 MethodInfo (我指的是实际模板,通用定义,而不是它的封闭特殊化)。我们试图在Foo类的诞生时获得(并成功)。

    private static readonly MethodInfo genericDefinitionOf_getData;

    static Foo() {
        Type prototypeQueryable = typeof(IQueryable<int>); 
        // this could be any IQuerable< something >
        // just had to choose one

        MethodInfo getData_ForInts = typeof(Foo).GetMethod(
            name: "GetData", 
            bindingAttr: BindingFlags.Static | BindingFlags.Public,
            binder: Type.DefaultBinder,
            types: new [] { prototypeQueryable, typeof(int), typeof(bool) },
            modifiers: null
        );
        // now we have the GetData<int>(IQueryable<int> data, int bar, bool bravo)
        // reffered by the reflection object getData_ForInts

        MethodInfo definition = getData_ForInts.GetGenericMethodDefinition();
        // now we have the generic (non-invokable) GetData<>(IQueryable<> data, int bar, bool bravo)
        // reffered by the reflection object definition

        Foo.genericDefinitionOf_getData = definition;
        // and we store it for future use
    }

然后我们编写该方法的非泛型变体,该变体应针对作为参数发送的实际元素类型调用特定的泛型方法:

    public static IQueryable GetDataEx(IQueryable data, int bar, bool bravo) {
        if (null == data)
            throw new ArgumentNullException("data");
        // we can't honor null data parameters

        Type typeof_data = data.GetType(); // get the type (a class) of the data object
        Type[] interfaces = typeof.GetInterfaces(); // list it's interfaces

        var ifaceQuery = interfaces.Where(iface => 
            iface.IsGenericType && 
            (iface.GetGenericTypeDefinition() == typeof(IQueryable<>))
        ); // filter the list down to just those IQueryable<T1>, IQueryable<T2>, etc interfaces
        Type foundIface = ifaceQuery.SingleOrDefault();
        // hope there is at least one, and only one

        if (null == foundIface) // if we find more it's obviously not the time and place to make assumptions
            throw new ArgumentException("The argument is ambiguous. It either implements 0 or more (distinct) IQueryable<T> particularizations.");

        Type elementType = foundIface.GetGenericArguments()[0];
        // we take the typeof(T) out of the typeof(IQueryable<T>)

        MethodInfo getData_particularizedFor_ElementType = Foo.genericDefinitionOf_getData.MakeGenericMethod(elementType);
        // and ask the TypeSystem to make us (or find us) the specific particularization
        // of the **GetData < T >** method

        try {
          object result = getData_particularizedFor_ElementType.Invoke(
              obj: null,
              parameters: new object[] { data, bar, bravo }
          );
          // then we invoke it (via reflection)

          // and obliviously "as-cast" the result to IQueryable
          // (it's surely going to be ok, even if it's null)
          return result as IQueryable;

        } catch (TargetInvocationException ex) {
          // in case of any mis-haps we make pretend we weren't here
          // doing any of this
          throw ex.InnerException;

          // rethink-edit: Actually by rethrowing this in this manner
          // you are overwriting the ex.InnerException's original StackTrace
          // so, you would have to choose what you want: in most cases it's best not to rethrow
          // especially when you want to change that which is being thrown
        }
    }


}
于 2013-02-23T21:01:24.800 回答