gpt4 book ai didi

json - 为什么转储此 JObject 会在 LINQPad 中引发 AmbiguousMatchException?

转载 作者:行者123 更新时间:2023-12-04 18:35:24 26 4
gpt4 key购买 nike

当我使用 JSON.NET 在 LINQPad 中运行此代码时:

var x = JObject.Parse(
@"{
""data"" : [ {
""id"" : ""bbab529ecefe58569c2b301a"",
""name"" : ""Sample Name"",
""group"" : ""8b618be8dc064e653daf62f9"",
""description"" : ""Sample Name"",
""payloadType"" : ""Geolocation"",
""contract"" : ""a9da09a7f4a7e7becf961865"",
""keepAlive"" : 0
} ]
}");

x.Dump();

当试图将解析的 JSON 转储到 LINQPad 的输出窗口时,将抛出 AmbiguousMatchException。为什么?据我所知,这是完全合法的 JSON。 http://jsonlint.com/说它也是有效的。

最佳答案

这很可能是 .Dump() 的实现方式有问题。

如果您检查堆栈跟踪:

at System.RuntimeType.GetInterface(String fullname, Boolean ignoreCase)
at System.Type.GetInterface(String name)
at UserQuery.Main()
...

我们可以看到抛出异常的方法是System.RuntimeType.GetInterface

System.RuntimeType 是在运行时使用反射时用于表示 Type 对象的具体类之一,所以让我们检查一下 Type.GetInterface(String, Boolean)有这样的话:

AmbiguousMatchException
The current Type represents a type that implements the same generic interface with different type arguments.

所以看起来 GetInterface 方法是用一种多次实现的接口(interface)类型调用的,具有不同的 T 或类似的。

要引发相同的错误,只需将 x.Dump(); 替换为:

var type = x.GetType().GetInterface("System.Collections.Generic.IEnumerable`1", true);

这将抛出相同的异常。

这是一个更简单的 LINQPad显示潜在问题的示例:

void Main()
{
var type = typeof(Problem).GetInterface("System.Collections.Generic.IEnumerable`1", true);
}

public class Problem : IEnumerable<string>, IEnumerable<int>
{
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<string>)this).GetEnumerator();
IEnumerator<string> IEnumerable<string>.GetEnumerator() => Enumerable.Empty<string>().GetEnumerator();
IEnumerator<int> IEnumerable<int>.GetEnumerator() => Enumerable.Empty<int>().GetEnumerator();
}

此示例将抛出完全相同的异常。


结论:Json 和 Json.Net 都没有问题,这是 LINQPad 试图找出将对象转储到输出窗口的最佳方式的问题。

关于json - 为什么转储此 JObject 会在 LINQPad 中引发 AmbiguousMatchException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39286645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com