集合
发表于:2025-10-12 | 分类: Dotnet
字数统计: 270 | 阅读时长: 1分钟 | 阅读量:

集合

所有实现了 ICollection 接口的类型都可称之为 集合

继承 IEnumerable 接口,代表集合类型都可以枚举方式迭代。

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\ICollection.cs

namespace System.Collections
{
// 所有集合的基础接口,定义了 enumerators, size, sync methods.
public interface ICollection : IEnumerable
{
// 从index开始拷贝至array中
void CopyTo(Array array, int index);

// 集合元素数量
int Count { get; }

// 锁对象,确保对集合的操作线程安全
object SyncRoot { get; }

// 标识集合是否是线程安全的,false则需通过 SyncRoot 手动实现同步
bool IsSynchronized { get; }
}
}

如何实现线程安全的?

1
2
3
4
5
6
7
8
9
10
// 所有对集合的修改(Add Remove Clear Clone...)都需要获取锁对象

// Hashtable为例
public override void Add(object key, object? value)
{
lock (_table.SyncRoot)
{
_table.Add(key, value);
}
}

对应的泛型接口:

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\ICollection.cs
namespace System.Collections.Generic
{
public interface ICollection<T> : IEnumerable<T>
{
int Count { get; }

bool IsReadOnly { get; }

void Add(T item);

void Clear();

bool Contains(T item);

void CopyTo(T[] array, int arrayIndex);

bool Remove(T item);
}
}
上一篇:
枚举
下一篇:
Api优化