将 Int64 值类型转换为 Newtonsoft.Json.Linq.JValue 时抛出 InvalidCast 异常

问题描述 投票:0回答:0

我正在将

Int64
值类型转换为
JValue
并且我能够对其进行类型转换。但是,当我将该 Int64 值存储在
object
类型的变量中,然后尝试对其进行类型转换时,为什么它会抛出 InvalidCast 异常?.

     Int64 Int64Value = Int64.MaxValue;

        // Int64 value can be TypeCasted to JValue
        Newtonsoft.Json.Linq.JValue output = (Newtonsoft.Json.Linq.JValue) Int64Value;
        
        // Storing Int64 value in variable of type object
        object Int64ValueInObject = Int64Value;

        try
        {
            // Why this code throws exception ?
            Newtonsoft.Json.Linq.JValue output1 = (Newtonsoft.Json.Linq.JValue)(Int64ValueInObject);
        }
        catch (InvalidCastException ex )
        {
            // {"Unable to cast object of type 'System.Int64' to type 'Newtonsoft.Json.Linq.JValue'."}
           // However, from above code it is seen that Int64 can be casted to JValue
        }
c# .net json.net
© www.soinside.com 2019 - 2024. All rights reserved.