我正在使用教程https://www.dotnetperls.com/dictionary中的示例
,但是我遇到了缺少对TryAdd. 我应该添加一些额外的参考来使用此方法吗?我在文档中没有找到任何内容https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.tryadd?view=net-5.0
var items = new Dictionary<string, int>();
// Part 1: add the string with value 1.
bool result = items.TryAdd("test", 1);
Run Code Online (Sandbox Code Playgroud)
严重性代码说明项目文件行抑制状态错误 CS1061“Dictionary<string, int>”不包含“TryAdd”的定义,并且没有可访问的扩展方法“TryAdd”接受类型为“Dictionary<string, int>”的第一个参数被发现(您是否缺少 using 指令或程序集引用?) CsharpTest C:\path\to\file\Program.cs 672 Active
更新:此方法适用于 .NET 5 及更高版本(我使用的是较旧的框架)