首页 > 解决方案 > 在(字典)索引器上使用 C# 的 ref 功能

问题描述

我想知道是否可以ref return在(字典)索引器或定义 asetget访问器的属性上使用 C#,例如:

readonly Dictionary<string, int> dictionary = ...;


ref int v = ref dictionary["foo"];
//          ^^^^^^^^^^^^^^^^^^^^^
// CS0206: A property or indexer may not be passed as an out or ref parameter
v = 42;

是否有可能以某种方式为ref属性或索引器提供功能(不使用反射)?如果是这样,怎么做?


我知道,从这个意义上说,错误消息很清楚 - 但是,我想知道哪种方法是实现其语义的最佳方式。

标签: c#ref

解决方案


这需要实现 indexer 的类型在 indexer提供 provider ref-return ,所以不:你不能将它与. 但是有这样的事情:Dictionary<string, int>

class MyRefDictionary<TKey, TValue>
{
    public ref TValue this[TKey key]
    {   // not shown; an implementation that allows ref access
        get => throw new NotImplementedException();
    }
}

你确实可以这样做:

ref var val = ref dictionary[key];

请注意,数组是一种特殊情况,因为数组始终允许 ref 索引器访问,即

SomeMethod(ref arr[42]);

(数组中的索引器访问由编译器实现,而不是类型)


推荐阅读