无法使用实例引用访问成员 'object.Equals(object, object)'
Member 'object.Equals(object, object)' cannot be accessed with an instance reference
[注意:有 another question about the same error-message,但问题的根本原因有点不同,none 的答案适用于以下代码。]
我有这个代码:
string localComputerName = Environment.MachineName;
foreach (StatsServer server in servers)
{
if (localComputerName.Equals(server, StringComparison.OrdinalIgnoreCase)) {
...
}
}
在调用 Equals
:
时给我这个编译错误
Member 'object.Equals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead
我原以为它会使用string.Equals(string, StringComparison),这是一个实例方法(不是静态方法);为什么编译器认为我想要 object.Equals(object, object) 而不是?
发生的事情是 string
是一个 object
,但它与 StatsServer
不是同一类型的 object
,因此 Visual Studio 感到困惑并且认为 localComputerName
变量是问题所在,而不是 server
.
据我所知,它是根据 Equals
方法的参数来决定的,而不是根据应用 Equals
的变量的数据类型来决定的。 (IMO,这是倒退的,但显然微软有他们的理由,并且可能与 Equals
如何 overloaded/extended 到所有 object
或其他东西有关。)
在这种情况下,错误是转移注意力的错误。需要发生的是我应该访问 server
的 ServerName
property/column,因为它是 string
并且具有我真正想要比较的数据:
if (localComputerName.Equals(server.ServerName, StringComparison.OrdinalIgnoreCase))
故事的寓意是确保您的 object
具有相同的数据类型,并在假设 JIT 编译器 100% 准确之前查看整行代码。
[注意:有 another question about the same error-message,但问题的根本原因有点不同,none 的答案适用于以下代码。]
我有这个代码:
string localComputerName = Environment.MachineName;
foreach (StatsServer server in servers)
{
if (localComputerName.Equals(server, StringComparison.OrdinalIgnoreCase)) {
...
}
}
在调用 Equals
:
Member 'object.Equals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead
我原以为它会使用string.Equals(string, StringComparison),这是一个实例方法(不是静态方法);为什么编译器认为我想要 object.Equals(object, object) 而不是?
发生的事情是 string
是一个 object
,但它与 StatsServer
不是同一类型的 object
,因此 Visual Studio 感到困惑并且认为 localComputerName
变量是问题所在,而不是 server
.
据我所知,它是根据 Equals
方法的参数来决定的,而不是根据应用 Equals
的变量的数据类型来决定的。 (IMO,这是倒退的,但显然微软有他们的理由,并且可能与 Equals
如何 overloaded/extended 到所有 object
或其他东西有关。)
在这种情况下,错误是转移注意力的错误。需要发生的是我应该访问 server
的 ServerName
property/column,因为它是 string
并且具有我真正想要比较的数据:
if (localComputerName.Equals(server.ServerName, StringComparison.OrdinalIgnoreCase))
故事的寓意是确保您的 object
具有相同的数据类型,并在假设 JIT 编译器 100% 准确之前查看整行代码。