[英]Prevent double lookup of the same element in Dictionary
I know there is no reference to "struct" variable
in C#, but this is the case where it would come handy 我知道C#中没有
reference to "struct" variable
,但是这种情况很方便
Dictionary<int, int> d = new Dictionary<int, int>();
d.Add(1, 1);
++d[1];
++d[1];
how can I perform 2 operations (increment in this case) on the same element without using operator[]
twice (to prevent double lookup)? 如何在同一元素上执行2次操作(在这种情况下为递增),而又没有使用
operator[]
两次(以防止重复查找)?
You can create a mutable reference type that wraps another value, in this case an immutable value type, allowing the value of the wrapper to be mutated: 您可以创建一个包装另一个值的可变引用类型,在这种情况下为不可变值类型,从而允许包装器的值发生突变:
public class Wrapper<T>
{
public T Value { get; set; }
}
This lets you write: 这使您可以编写:
Dictionary<int, Wrapper<int>> d = new Dictionary<int, Wrapper<int>>();
d.Add(1, new Wrapper<int>(){Value = 1});
var wrapper = d[1];
wrapper.Value++;
wrapper.Value++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.