Ale*_*100 7 .net c# dictionary
我正在使用教程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 及更高版本(我使用的是较旧的框架)
V0l*_*dek 17
评论是半正确的。此方法是在 .NET Core 2.0 和 .NET Standard 2.1 中引入的,因此您的目标框架至少需要这样。特别是,它不存在于 .NET Framework(任何版本)上,但存在于最新的 .NET 5 上。
如果您在较旧的运行时中需要它,您可以编写一个扩展方法(取自dotnet/runtime、System.Collections.Generic.CollectionExtensions)。
public static bool TryAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
if (!dictionary.ContainsKey(key))
{
dictionary.Add(key, value);
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
它的性能特征比 的实例方法更差Dictionary<,>,因为它首先执行单独的查找,但不太可能相关。