c#怎么写Dictionary的扩展方法
时间: 2024-06-01 17:04:09 浏览: 10
以下是一个示例,演示如何编写C#中Dictionary的扩展方法:
```csharp
using System.Collections.Generic;
public static class DictionaryExtensions
{
public static TValue GetValueOrDefault<TKey, TValue>(
this IDictionary<TKey, TValue> dictionary,
TKey key,
TValue defaultValue = default(TValue))
{
TValue value;
return dictionary.TryGetValue(key, out value) ? value : defaultValue;
}
}
```
这个扩展方法名为`GetValueOrDefault`,它接受一个键和一个可选的默认值,并返回与该键关联的值(如果存在),否则返回默认值。要使用此扩展方法,请将其添加到您的代码中,并在需要时调用它,如下所示:
```csharp
var dict = new Dictionary<string, int>();
dict.Add("one", 1);
dict.Add("two", 2);
int value = dict.GetValueOrDefault("three", 3);
// value 现在为 3,因为 "three" 不存在于字典中
```