[英]Custom Equals Method in C#
我编写了一个名为baseCommodity
的类,它包含一个自定义的Equals
方法:
public override bool Equals(object obj)
{
BaseCommodity other = obj as BaseCommodity;
return other != null && other.GetType() is this.GetType());
}
我想将other.GetType()
与this
的类型进行比较,但是is this.GetType()
无法正常工作。 我不断收到错误消息“ this', expecting
符号为意外符号this', expecting
类型为”。
您想要==
代替:
return other != null && other.GetType() == this.GetType();
当您知道可以检查的对象的编译时类型标记时,可以使用is
。
附带说明一下,如果要覆盖Equals(object other)
,也许您还想实现IEquatable<BaseCommodity>
并覆盖它的Equals(BaseCommodity other)
,这样可以节省类型检查。
另外,这是一个非常弱的类型相等性检查。
也许更多的信息将是一个很好的答案。
GetType
返回类型对象 ,而不是类型标记 。 类型标记使用is
进行处理,类型对象使用相等(==)进行比较。
换一种说法:
object a = 12893;
if (a is int) // compare by token:
{ ... }
和
object a = 12345;
if (a.GetType() == typeof(int)) // compare by equality of type object.
{ ... }
PS:平等会给继承带来奇怪的结果。 在这种情况下,您可能要改用SomeType.IsAssignableFrom
。
正如其他人所述,这里需要比较运算符==
。
is
是类型检查,它与左侧的变量和右侧的类型一起使用:
string s = "";
bool isString = s is string;
请注意, GetType
的结果不是类型 ,它是代表类型的变量 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.