[英]How to pass a anonymous object into a generic function?
从Tim Corey 的ASP.NET 和精巧的教程开始,我改编了一个通用的 function 来将数据存储在 SQL 服务器数据库中,以返回存储的 object 的 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 });
应该怎么做? 我是否必须使用显式类型而不是匿名类型 object?
编辑:返回值是通用的原因,因为 ID 可以是例如int
、 long
或string
GUID。
我必须同意“这里的参数只使用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!
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.