Char.Equals 与 Object.Equals——ReSharper 建议我应该使用 Object.Equals。我应该吗?
基本上,我想知道在这种情况下我是否应该听 ReSharper...
您会发现与字符相比应该使用 Char.Equals(char) 因为它可以避免拆箱,但 Resharper 建议使用 Object.Equals(obj) 。也许我在这里遗漏了一些东西?
private const DEFAULT_CHAR = '#';
// DependencyProperty backing
public Char SpecialChar
{
get { return (Char)GetValue(SpecialCharProperty); }
}
// ReSharper - Access to a static member of a type via a derived type.
if (Char.Equals(control.SpecialChar, DEFAULT_CHAR)) { ... }
我猜这是因为有 DependencyProperty 支持?
Basically, I'm wondering if I should listen to ReSharper in this instance...
You'd figure that comparing to characters one should use Char.Equals(char) since it avoids unboxing, but Resharper suggests using Object.Equals(obj). Maybe I'm missing something here?
private const DEFAULT_CHAR = '#';
// DependencyProperty backing
public Char SpecialChar
{
get { return (Char)GetValue(SpecialCharProperty); }
}
// ReSharper - Access to a static member of a type via a derived type.
if (Char.Equals(control.SpecialChar, DEFAULT_CHAR)) { ... }
I'm guessing it's because there is a DependencyProperty backing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不可能覆盖
static
成员 -Object.Equals()
是静态成员,并且Char
不能 覆盖它,即使您可以在 Char 类型上调用它(参数仍然是Object
类型)调用都没有区别
因此,无论您调用还是
,因为装箱将发生在无论哪种情况。
为了避免这种情况,请使用实例方法,该方法在
Char
中被重写:It is impossible to override
static
members -Object.Equals()
is a static member, andChar
cannot override it, even though you can call it on the Char type (the params are still of typeObject
)Therefore, it makes no difference whether you call
or
since boxing will occur in either case.
To avoid this, use the instance method, which is overridden in
Char
:Char.Equals(control.SpecialChar, DEFAULT_CHAR)
是对Object.Equals(object, object)
的调用,因此 resharper 在这里是正确的。我建议使用
control.SpecialChar.Equals(DEFAULT_CHAR)
或者只是
DEFAULT_CHAR == control.SpecialChar
Char.Equals(control.SpecialChar, DEFAULT_CHAR)
is a call toObject.Equals(object, object)
, so resharper is correct here.I would suggest to use
control.SpecialChar.Equals(DEFAULT_CHAR)
or just
DEFAULT_CHAR == control.SpecialChar