我有时会创建这样一个类,几乎是逐字逐句的,尽管我将类Holder<T>
和字段称为Value
;这样的类有两个很好的用例:
给定 的集合Holder<someValueType>
,可以方便地对集合的内容进行就地修改。例如,给定一个List<Holder<Point>>
,可以说MyList[3].Value.X += 5;
。
如果T
是一种允许原子操作的类型,Holder<T>
即使该集合不是线程安全的,也可以对集合的内容执行线程安全的原子操作。例如,在我事先知道字典所需的所有键的情况下,我创建了一个Dictionary<String, Holder<Integer>>
,然后可以使用多个线程Interlocked.Increment
来计算每个字符串出现的次数。尽管Dictionary
不是线程安全的,但该程序在没有锁定的情况下是线程安全的,因为Holder<Integer>
存储在字典中的项目集永远不必更改。
If you want to use a built-in type, there is one that would work: a T[]
with size one. The main disadvantage of that type is that there's nothing inherent in the type which guarantees that element zero will actually exist (i.e. that it won't be an empty array).