gpt4 book ai didi

c# - 是什么导致这里出现 "extension methods cannot be dynamically dispatched"?

转载 作者:IT王子 更新时间:2023-10-29 04:12:52 25 4
gpt4 key购买 nike

编译错误

'System.Data.SqlClient.SqlConnection' has no applicable method named 'Query' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

现在,我知道如何解决该问题,但我正试图更好地了解错误本身。我有正在构建的类来利用 Dapper。最后,我将提供一些更多的自定义功能,使我们的数据访问类型更加简化。特别是建立跟踪和东西。然而,现在就这么简单:

public class Connection : IDisposable
{
private SqlConnection _connection;

public Connection()
{
var connectionString = Convert.ToString(ConfigurationManager.ConnectionStrings["ConnectionString"]);
_connection = new SqlConnection(connectionString);
_connection.Open();
}

public void Dispose()
{
_connection.Close();
_connection.Dispose();
}

public IEnumerable<dynamic> Query(string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
{
// this one works fine, without compile error, so I understand how to
// workaround the error
return Dapper.SqlMapper.Query(_connection, sql, param, transaction, buffered, commandTimeout, commandType);
}

public IEnumerable<T> Query<T>(string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
{
// this one is failing with the error
return (IEnumerable<T>)_connection.Query(sql, param, transaction, buffered, commandTimeout, commandType);
}
}

但有趣的是,如果我简单地发表这样的声明:

_connection.Query("SELECT * FROM SomeTable");

它编译得很好。

那么,有人能帮我理解为什么在那些其他方法中利用相同的重载会失败并出现该错误吗?

最佳答案

So, can somebody please help me understand why leveraging the same overload inside of those other methods is failing with that error?

正是因为您使用动态值 (param) 作为参数之一。这意味着它将使用动态调度...但扩展方法不支持动态调度。

虽然解决方案很简单:直接调用静态方法即可:

return SqlMapper.Query(_connection, sql, param, transaction,
buffered, commandTimeout, commandType);

(假设您确实需要 paramdynamic 类型,当然......如评论中所述,您可能只需将其更改为对象。)

关于c# - 是什么导致这里出现 "extension methods cannot be dynamically dispatched"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15391115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com