字典
发表于:2025-10-13 | 分类: Dotnet
字数统计: 345 | 阅读时长: 1分钟 | 阅读量:

字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

namespace System.Collections
{
// 无序的键值对集合,key可为任意非空对象,value可为任意对象
public interface IDictionary : ICollection
{
// 提供读写字典元素的方法
object? this[object key] { get; set; }

// 字典的key集合
ICollection Keys { get; }

// 字典的value集合
ICollection Values { get; }

// 是否包含指定key
bool Contains(object key);

// 添加键值对
void Add(object key, object? value);

// 移除所有键值对
void Clear();

// 是否只读
bool IsReadOnly { get; }

// 是否固定大小
bool IsFixedSize { get; }

// 返回 IDictionaryEnumerator 枚举器
new IDictionaryEnumerator GetEnumerator();

// 移除指定key的元素
void Remove(object key);
}
}

对应的泛型接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\IDictionary.cs
namespace System.Collections.Generic
{
public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>
{
TValue this[TKey key] { get; set; }

ICollection<TKey> Keys { get; }

ICollection<TValue> Values { get; }

bool ContainsKey(TKey key);

void Add(TKey key, TValue value);

bool Remove(TKey key);

bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value);
}
}

字典中的键值对:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// \runtime\src\libraries\System.Private.CoreLib\src\System\Collections\Generic\DictionaryEntry.cs
namespace System.Collections
{
// 字典的key-value 对
// 由 IDictionaryEnumerator::GetEntry() 返回
public struct DictionaryEntry
{
private object _key;
private object? _value;

public DictionaryEntry(object key, object? value) { _key = key; _value = value; }

public object Key { get => _key; set => _key = value; }

public object? Value { get => _value; set => _value = value; }

public void Deconstruct(out object key, out object? value) { key = Key; value = Value; }

public override string ToString() => KeyValuePair.PairToString(_key, _value);
}
}
上一篇:
队列
下一篇:
列表