c# - 在(字典)索引器上使用 C# 的 ref 功能
问题描述
我想知道是否可以ref return
在(字典)索引器或定义 aset
和get
访问器的属性上使用 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
属性或索引器提供功能(不使用反射)?如果是这样,怎么做?
我知道,从这个意义上说,错误消息很清楚 - 但是,我想知道哪种方法是实现其语义的最佳方式。
解决方案
这需要实现 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]);
(数组中的索引器访问由编译器实现,而不是类型)
推荐阅读
- javascript - google Apps 脚本使用 mailApp 发送 htmlbody(正在修改的内容)
- node.js - 我无法删除用户身份验证
- python - 在函数本身中更改函数输入
- javascript - 使用 Basecamp / Trix 编辑器时“未定义新的 Trix”
- c++ - C++, = 运算符不同的选项
- pytorch - Detectron2 在我的 model_final.pth 中添加更多类或微调现有类
- javascript - 从三个句子中间取出单词的最快方法是什么?/ 操作字符串
- python - 尝试使用ride.py 从命令提示符启动 RIDE 时出错
- c++ - 如何使用 Eigen 提高我的性能?(包括示例代码)
- pytorch - 为优化器加载状态字典时的 Pytorch / 设备问题(cpu,gpu)