2015-07-03 68 views
3

我试图在Dapper上创建一个图层并希望创建一个使用QueryMultiple方法的方法。我想使用QueryMultiple的Read方法将传入的字符串格式的列表(在运行时确定)映射。当试图使用Read方法时,我无法找到使泛型参数接受我创建的类型的方法。当使用Dapper QueryMultiple时提供泛型参数的类型

任何人都可以请帮助我如何正确提供类型?

下面的代码:

using (SqlConnection conn = GetNewConnection()) 
{ 
    conn.Open(); 
    var multi = conn.QueryMultiple(sql, param); 
    foreach (string typeName in ListOfTypes) //Iterate a List of types in string format. 
    { 
     Type elementType= Type.GetType(typeName); 
     var res= multi.Read<elementType>(); //Error: The type or namespace name 'combinedType' could not be found (are you missing a using directive or an assembly reference?) 
     //Add result to a dictionary 
    } 
} 

回答

2

当前正在使用的QueryMultiple.Read<T>()方法需要必须在编译时已知的一般类型参数。换句话说,elementType不能被用作<T>参数内的一般类型参数:

Type elementType = Type.GetType(typeName); 
var res = multi.Read<elementType>(); // /Error: The type or namespace... etc. 

如果类型不知道直到运行时,使用QueryMultiple.Read(Type type)方法:

Type elementType = Type.GetType(typeName); 
var res = multi.Read(elementType); 

见MSDN更多信息Generic Type Parameters

+0

谢谢!这真的起作用了。也感谢泛型解释真的很有帮助。 – Jimmy

+0

欢迎来到StackOverflow,感谢您的关注! –