從Tim Corey 的ASP.NET 和dapper 教程開始,我調整了一個通用函式來將資料存盤在 SQL Server 資料庫中,以回傳存盤物件的 ID:
public async Task<T> SaveData<T, U>(
string storedProcedure,
U parameters,
string connectionId = "DefaultDataConnection")
{
using IDbConnection connection = new SqlConnection(_configuration.GetConnectionString(connectionId));
T ID = await connection.ExecuteScalarAsync<T>(storedProcedure, parameters, commandType: CommandType.StoredProcedure);
return ID;
}
問題如下:在教程的原始代碼中,可以在不宣告泛型引數型別的情況下呼叫該方法。但是,對于附加的通用回傳型別,這是沒有必要的。問題是,這些方法通常是用匿名型別物件呼叫的,我不知道如何呼叫該方法:
// this is within the insert method of my class, which is responsible for handling the images table:
int insertedID = await _db.SaveData<int, ????>("dbo.spImage_Insert", new { image.UserID, image.FileName, image.UploadDate });
應該怎么做?我必須使用顯式型別而不是匿名物件嗎?
編輯:回傳值是通用的原因,因為 ID 可以是例如int,long或stringGUID。
uj5u.com熱心網友回復:
我必須同意“僅object用于此處的引數”的評論,但是;在更一般的情況下:
要在此處使用匿名物件執行您想要的操作,您需要將 API 分成兩部分;例如,而不是SaveData<T, U>考慮:
int x = Save(new { image.UserID, image.FileName, image.UploadDate })
.Expect<int>();
這可以實作為:
NamingIsHard<T> Save<T>(T x);
和
public readonly struct NamingIsHard<T>
{
T theT; // and other things; possibly the connection, etc
// ...
public U Expect<U>() {
// here you have a T and a U; do your thing!
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/435078.html
