如何从字符串myTElementName获取TElement?

时间:2011-09-12 15:26:17

标签: c# entity-framework generics

我想为entityframework创建一个通用查询构建器。对于以下方法ObjectContext.ExecuteStoreQuery<TElement> Method (String, Object[])我试图传递泛型类型。那就是:

BindingSource mybindingSource = new BindingSource();

mybindingSource.DataSource = 
    con.ExecuteStoreQuery<**SomeMethod**(MyTypeName)>(
        myperfectWorkingSql, 
        myperfectWorkingSqlsParams
    );

如何从字符串MyTypeName获取TElement?我的SomeMethod()函数应该如何?或者我应该使用哪种方法?

或以下代码也会出错?我错了吗?

 function fooo ( Type t) {

 BindingSource mybindingSource = new BindingSource();

mybindingSource.DataSource = 
    con.ExecuteStoreQuery<t>(
        myperfectWorkingSql, 
        myperfectWorkingSqlsParams
    );
 }

ERROR: this gives type t or namespace t can not be found !

1 个答案:

答案 0 :(得分:1)

由于您希望从字符串中获取类型,因此它将在运行时解析,因此您无法执行此类操作con.ExecuteStoreQuery<t>。但是,您可以使用反射来调用此方法并将类型提供为通用参数

Refer to this answer on how to invoke generic method via reflection