Stunning Int64.Equals Behavior

Why does this test not work?

    [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 Int32Keys
    {
        public Int32 Id { get; set; }
    }
    public class DoubleKeys
    {
        public double Id { get; set; }
    }

I answered this question, but did not get enough idea to fix it.

Edit: I am using a repository template, so my instance can be of any type (Int32, Int64, double).

+3
source share
3 answers

Type IDValuewill be object- because he PropertyInfodoes not know anything better. Therefore you call object.Equals(object)for IDValue.Equals(0). In this box, the value of Int32 is 0 ... and overriding Equals(object)in Int64checks that it is valid Int64with which you are comparing it. This is not the case in this case, so it returns false.

, Equals(0L), true.

, IDValue Int64, true, Int64.Equals(Int64), Int32 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        
    }
}
+3

long int. , . :

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

:

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

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

+1
source

Source: https://habr.com/ru/post/1776163/


All Articles