如何将匿名对象传递给泛型函数?

Rol*_*ain 0 c# generics anonymous-types dapper

根据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;
}
Run Code Online (Sandbox Code Playgroud)

问题如下:在教程的原始代码中,可以在不声明泛型参数类型的情况下调用该方法。然而,对于附加的泛型返回类型,这是没有必要的。问题是,这些方法通常是用匿名类型对象调用的,我不知道如何调用该方法:

// 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 });
Run Code Online (Sandbox Code Playgroud)

应该怎样做呢?我是否必须使用显式类型而不是匿名对象?

编辑:返回值是通用的,因为 ID 可以是int,longstringGUID。

Mar*_*ell 6

我必须同意“仅用于object此处的参数”的评论,但是;在更一般的情况下:


要使用匿名对象执行您想要的操作,您需要将 API 一分为二;例如,不要SaveData<T, U>考虑:

int x = Save(new { image.UserID, image.FileName, image.UploadDate })
          .Expect<int>();
Run Code Online (Sandbox Code Playgroud)

可以实现为:

NamingIsHard<T> Save<T>(T x);
Run Code Online (Sandbox Code Playgroud)

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!
    }
}
Run Code Online (Sandbox Code Playgroud)