JsonObject's ICollection<KeyValuePair<string, JsonNode?>>.Remove ignores the value

未关闭 适合新手
#138,090 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
82/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
csharp
领域
backend

调研方向

从 JsonObject.IDictionary.cs 开始,查看显式实现的 ICollection<KeyValuePair<string, JsonNode?>>.Remove 方法,它目前调用 Remove(item.Key) 而不检查值。将其与上方的 Contains 方法进行比较,后者会检查键和节点引用。在 JsonObjectTests 中为键匹配但值不同的情况添加测试,并运行该测试类。完成标准是:该情况返回 false 且属性保持不变,而完全匹配的键值对仍会被移除并分离。

由索引模型根据 Issue 内容生成。

描述

area-System.Collections untriaged
Description

JsonObject's explicit ICollection<KeyValuePair<string, JsonNode?>>.Remove(item) removes the property with the matching key even when the value doesn't match. Contains(item) on the same interface does check the value, and Dictionary<,> and OrderedDictionary<,> return false from Remove in this case.

Reproduction Steps
using System.Text.Json.Nodes;

var obj = new JsonObject { ["a"] = 1, ["b"] = 2 };
ICollection<KeyValuePair<string, JsonNode?>> collection = obj;
var other = new KeyValuePair<string, JsonNode?>("b", JsonValue.Create(99));

Console.WriteLine(collection.Contains(other));
Console.WriteLine(collection.Remove(other));
Console.WriteLine(obj.ToJsonString());
Expected behavior
False
False
{"a":1,"b":2}
Actual behavior
False
True
{"a":1}

Seen on .NET 10.0.15 and 11.0.0. For comparison, ((ICollection<KeyValuePair<string, int>>)new Dictionary<string, int> { ["a"] = 1, ["b"] = 2 }).Remove(new("b", 99)) returns false and keeps both entries, and so does OrderedDictionary<string, int>.

Other information

In JsonObject.IDictionary.cs the method is => Remove(item.Key);, while its XML docs say it removes "the property name and value" represented by the KeyValuePair. Contains right above it documents that it checks the property name and JsonNode reference, and it does: a different node with an equal value also returns false. The existing test in JsonObjectTests removes a pair that matches and a key that doesn't exist, but not a matching key with a different value.

A possible fix is to return false unless Contains(item) is true (so the same reference semantics as Contains), then remove by key as today so the node is still detached from its parent. I can send a PR with a test if you'd like.

主要语言
C#
星标
18.5k
派生
5.8k
平均合并
2 天 18 小时
30 天内合并 PR
588

环境准备

在 Codespaces 中打开

在浏览器里用你自己的 GitHub 账号启动这个项目的开发容器。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

dotnet/runtime 的其他 Issue

查看 dotnet/runtime 的全部 Issue

相似的 Issue

更多 C# Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。