现在,我有两个函数在一起:
bool HasX(int key) { ... }
ref S GetX(int key) { ... } // S is a struct
它们可以工作,但是当我需要在调用get函数之前检查是否存在时,它需要计算到数组中的偏移量并检查两次值。这就是为什么像Dictionary<TK, TV>.TryGetValue(TK key, out TV value)
这样的函数存在的原因,所以只需要一次查找。
我试着把它们合二为一:
// ref S here has different semantics, I'm not able to set it to a ref structure handle
bool TryGetX(int key, ref S value)
// out S here has different semantics, it's a value copy for structs
bool TryGetX(int key, out S value)
// ref S here has different semantics, I'm not able to set it to a ref structure handle
bool TryGetX(int key, ref S value)
// copy again rather than reference
S? TryGetX(int key)
// equivalent to ref Nullable<S>, not Nullable<ref S>, so again not suitable
ref S? TryGetX(int key)
// this works, but it's backwards from normal, and I'm unable to write it cleanly
// as a condition, like: if(dict.TryGetValue(key, out var value)) { /* use value here */ }
ref S TryGetX(int key, out bool found)
// perhaps the cleanest so far, and return Unsafe.NullRef<S> for failure.
// still not idiomatic though
ref S TryGetX(int key)
是否有一种方法可以为ref
结构编写传统的TryGet
函数?
如果您想从运行时获得灵感,CollectionsMarshal.GetValueRefOrNullRef
(它获得对字典中条目的引用)如果未找到条目(可以使用Unsafe.IsNullRef<TValue>()
检测)返回Unsafe.NullRef<TValue>()
。