gpt4 book ai didi

c# - 应该和 Json.NET : This passes? ! JToken.Parse ("{}").ShouldBe ("hello");

转载 作者:行者123 更新时间:2023-11-30 15:31:53 24 4
gpt4 key购买 nike

谁能解释 Newtonsoft.Json.Linq.JToken 之间的这种奇怪的相互作用? (来自 Json.NET 4.5)和 Shouldly 1.1.1.1?

这是完整的 C# 代码:

using Newtonsoft.Json.Linq;
using NUnit.Framework;
using Shouldly;

public class Tests
{
[Test]
public void this_test_passes()
{
JToken.Parse("{}").ShouldBe("hello");
}
}

注意:字符串"hello" 并不特殊,它可以是任何字符串。

我猜这与隐式转换为某种覆盖 Equals(...) 的类型有关,以便为所有字符串返回 true,或其他。但这是我能做的最好的,谁能解释这里到底发生了什么?

编辑:我已经提交了 a patch for this issue , 如果合并到 master 中,将再次更新。

更新:问题已为下一个版本修复...:) https://github.com/shouldly/shouldly/issues/65#issuecomment-34579229

最佳答案

请注意,此通用类型解析给出:

JToken.Parse("{}").ShouldBe<JToken>("hello");

使用 string 中的隐式转换运算符至 JToken - 所以我们实际上是在比较两个 JToken s,不是 JToken和一个 string .

失败是因为 JToken : IEnumerable<JToken> ,指的是子 token 。因此,NUnit 决定执行序列相等性测试。对于这两者,都没有子序列:

JToken x = JToken.Parse("{}");
Console.WriteLine(x.Any()); // False
JToken y = "hello";
Console.WriteLine(y.Any()); // False

两个空序列通常被认为是相等的。

信息(来自元数据,而非来源):

public abstract class JToken : IJEnumerable<JToken>,
System.Collections.Generic.IEnumerable<JToken>, IEnumerable,
IJsonLineInfo, ICloneable, IDynamicMetaObjectProvider
{
// ...
public static implicit operator JToken(string value);
// ...
}

关于c# - 应该和 Json.NET : This passes? ! JToken.Parse ("{}").ShouldBe ("hello");,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19998878/

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