Json.NET隐式转换 [英] Json.NET implicit casting
问题描述
我有此代码:
class Sometype
{
public Number pos { get; set; }
}
class Number
{
private uint num;
private Number(uint num)
{
this.num = num;
}
public static implicit operator uint(Number sid)
{
return sid.num;
}
public static implicit operator Number(uint id)
{
return new Number(id);
}
}
这个json:{"pos":123}
当我尝试反序列化时,我得到了JsonException Error converting value 123 to type 'Tester2.Program+Number'.
.请告诉我.
When I try to deserialize this, I get a JsonException Error converting value 123 to type 'Tester2.Program+Number'.
. Please advise me.
推荐答案
如果添加从long
到Number
的implicit
(或explicit
)转换,则可以正常工作.
If you add an implicit
(or explicit
) conversion from long
to Number
, this will work fine.
JSON.NET与long
一起使用,因此永远不会调用您从uint
进行的转换.例如:
JSON.NET works with long
s when dealing with integral types, not uint
s, and so your cast from uint
is never called. For example:
class Number
{
private uint num;
private Number(uint num)
{
this.num = num;
}
public static implicit operator Number(uint id)
{
return new Number(id);
}
public static implicit operator Number(long id)
{
return new Number((uint)id);
}
public static implicit operator uint(Number sid)
{
return sid.num;
}
}
显然,这可能会导致溢出错误,因此请小心.另一个解决方案是创建一个自定义转换器来处理此问题(如果要序列化和反序列化此类型,可能值得研究).
Obviously this could result in overflow errors, so be careful. Another solution would be to create a custom converter to handle this (might be worth looking into if you're serializing and deserializing this type).
这是一个可行的示例: https://dotnetfiddle.net/MP4E3N
这篇关于Json.NET隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!