开发者

Weird Int64.Equals behaviour

Why this test is failing?

    [Test]
    public void Int64Test()
    {

        Int64Keys ObjBigInt = new Int64Keys();
        ObjBigInt.Id = 0;
        PropertyInfo p = ObjBigInt.GetType().GetProperty("Id");
        var IDValue = p.GetValue(ObjBigInt, null);
       //var IDType = IDValue.GetType(); //returns {System.Int64}
        Assert.IsTrue(IDValue.Equals(0)); //is returning  false and the type if IDValue is Int64()


    }

   public class Int64Keys
    {
        public Int64 Id { get; set; }
    }
   public class Int开发者_如何学JAVA32Keys
    {
        public Int32 Id { get; set; }
    }
    public class DoubleKeys
    {
        public double Id { get; set; }
    }

I referred this question but not getting enough idea to fix this.

Edit: I am using Repository pattern so my instance could be any type(Int32,Int64, double).


You are comparing a boxed long to an int. Boxed primitives will compare not-equal to any object that is not exactly of its own type. Change this line:

Assert.IsTrue(IDValue.Equals(0));

To this:

Assert.IsTrue(IDValue.Equals(0L));


The type of IDValue will be object - because PropertyInfo doesn't know any better. You're therefore calling object.Equals(object) for IDValue.Equals(0). That's boxing the Int32 value 0... and the override of Equals(object) in Int64 checks that it really is an Int64 you're comparing it with. In this case it's not, so it's returning false.

As other answers have said, use Equals(0L) to make it return true.

Note that if IDValue were strongly typed as Int64, it would already be returning true - because then the compiler would prefer the call to Int64.Equals(Int64), promoting the Int32 to an Int64:

using System;

class Test
{
    static void Main()
    {
        Int64 i64 = 0L;
        Console.WriteLine(i64.Equals(0)); // True

        object boxed = i64;
        Console.WriteLine(boxed.Equals(0)); // False
        Console.WriteLine(boxed.Equals(0L)); // True        
    }
}


Try Assert.IsTrue(IDValue.Equals(0L));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜