2015-07-03 86 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,感謝您的關注! –

相關問題