与Generics和Linq有关的问题

时间:2012-02-06 08:42:33

标签: c# .net vb.net

我有类名列表如下:

Type[] typelist = typeof(Sample.Students).Assembly.GetTypes();

现在我有Sample NameSpace中可用的所有类的完整列表:

现在我想通过课程获取数据 我正在使用Devexpress Persistance类 所以基本上我必须按如下方式创建XPQuert对象:

XPQuery<Employee> EmployeeQuery = new  XPQuery<Employees>(XPODefault.Session);

但在我的情况下,Employee类将列在typelist变量中.. 我如何创建XPQuery的对象..这可能是这样的:

XPQuery<typeof(typelist[0].Name)> EMployeeQuery = new XPQuery<typeof(typelist.Name)> (XPODefault.Session);

我的意思是我想动态创建对象..我该怎么办? 感谢..

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

public static IQueryable CreateQueryInstance(Type queryType) 
{
    var genericQueryTypeDefinition = typeof(XPQuery<>);
    var queryTypeArguments = new[] { typeof(queryType) };
    var genericQueryType = genericQueryTypeDefinition.MakeGenericType(queryTypeArguments);
    var queryObject = (IQueryable)Activator.CreateInstance(genericQueryType, <your parameters here>);

    return queryObject;
}

然后将其用作:

var myQueryObject = CreateQueryInstance(typelist[0]);

当然,你不可能有一个很好的XPQuery,因为你在编译时不知道类型,但你仍然可以从IQueryable开始。

答案 1 :(得分:1)

您可以使用反射来动态构建泛型类型。

Type queryType = typeof(XPQuery<>);
Type[] typeArgs = { typelist[0] };

Type constructed = queryType .MakeGenericType(typeArgs);
object myQuery = Activator.CreateInstance(constructed, XPODefault.Session);

您需要使用CreateInstance(type, params Object[] args)重载,以便指定构造函数所需的参数。

唯一的问题是返回的CreateInstance类型是object类型。 如果您想在myQuery上调用任何其他方法,则需要使用反射或dynamic关键字。

相关问题