3

当我使用 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();

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

4

1 回答 1

4

这是.Dump()最有可能如何实现的问题。

如果您检查堆栈跟踪:

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

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

System.RuntimeTypeType是在运行时使用反射时用来表示对象的具体类之一,所以让我们检查一下Type.GetInterface(String, Boolean)哪个有这个说法:

AmbiguousMatchException
当前 Type 表示一种类型,该类型实现了具有不同类型参数的相同泛型接口。

因此,看起来该GetInterface方法是使用一种多次实现的接口类型调用的,具有不同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 如何尝试找出将对象转储到输出窗口的最佳方法的问题。

于 2016-09-02T07:41:33.643 回答