为什么(((object)(int)1).Equals((((object)(ushort)1)))产生false? [英] Why does ((object)(int)1).Equals(((object)(ushort)1)) yield false?

查看:108
本文介绍了为什么(((object)(int)1).Equals((((object)(ushort)1)))产生false?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的情况是我有一个对象,我想检查与另一个对象的相等性。 / p>

I have the Situation that I have an object which I want to check for equality with another object.

public static bool Equals(object a, object b)
{
    return a.Equals(b);
}

A当 a = 1(整数)时出现问题 b = 1(超短(或基本上不是整数))。我想知道是否不应该得出true,但是它确实返回false ...

A Problem occurs when a = 1 (integer) and b = 1 (ushort (or basically not integer)). I wondered whether this shouldn't yield true, but it does return false...

编辑

更糟糕的是:

Hashtable ht = new Hashtable();
ht.Add((int)1, "SOME STRING");
ht.Add((short)1, "SOME STRING");
ht.Add((long)1, "SOME STRING");

我认为值 1只能被允许一次。

I think that the value '1' should only be allowed once.

推荐答案

Int32.Equals(object) 仅在另一个对象也是 Int32 的实例时返回true :

Int32.Equals(object) returns true only if the other object is also an instance of Int32:


如果obj是Int32的实例并且等于此
实例的值,则为true;否则为false。

true if obj is an instance of Int32 and equals the value of this instance; otherwise, false.

在代码中( ILSpy ,. NET 4):

In code (ILSpy, .NET 4):

public override bool Equals(object obj)
{
    return obj is int && this == (int)obj;
}

因为 obj是int 返回false会得到 false

Since obj is int returns false you get a false.

编辑:正在编辑( Hashtable (带有相似键)):如果您不想允许重复的对象,请使用 Dictionary< int,string> (首选)或仅将整数添加到 HashTable

Edit: ragarding to your edit(Hashtable with "similar" keys): if you don't want to allow duplicate objects use a Dictionary<int, string> instead(preferred) or add only ints to the HashTable.

这篇关于为什么(((object)(int)1).Equals((((object)(ushort)1)))产生false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆