我正在尝试在 dapper 上创建一个层,并想创建一个使用 QueryMultiple 方法的方法。我想使用 QueryMultiple 的 Read 方法以字符串格式(在运行时确定)映射传入的类型列表。尝试使用 Read 方法时,我找不到让泛型参数接受我正在创建的类型的方法。
任何人都可以帮助我如何正确提供类型吗?
代码如下:
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
}
}
最佳答案
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);
有关 Generic Type Parameters 的更多信息,请参阅 MSDN .
关于c# - 使用 Dapper QueryMultiple 时在泛型参数中提供类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31213924/