我正在构建一个使用 .dll 与盒子通信的应用程序。将盒子视为一个黑盒子,您需要知道的是我可以使用 dll 函数和引用访问盒子的内存。
现在,我的应用程序需要有一个字典(如果需要,我考虑用数组替换),其中包含位于框内存中的结构。我需要使用引用将结构从集合传递到框,然后框将更新结构的数据。问题是我无法直接将集合中的条目作为引用传递,因为它是动态成员。
我考虑过将集合中的一个元素作为本地成员传递,该元素将作为引用传递,并且在框更新后,我将根据需要更新自己的结构,但我宁愿将引用传递给直接结构。
如何直接将引用传递给集合中的元素?
最佳答案
无需使用ref
,只需传递您的 Dictionary<TKey, TValue>
通常,由于它本身就是一个引用类型,您的盒子所做的任何修改都会随后反射(reflect)在您的字典中!
例如
myBox.DoStuffWith(myDictionary);
// changes to a particular value in dictionary will be accessible, e.g.
Console.WriteLine(((StructType)myDictionary[myKey].Value).Member);
更新:
以下评论:
the function look like this: UpdateMessage(ref message)
你可以这样做:
Message msg = myDictionary[id];
UpdateMessage(ref msg);
myDictionary[id] = msg
更新2:
你说过你想避免这种情况。 Extension methods专为您无法控制类型(DLL 中带有 Update() 的类型,我们称之为 MessageUpdater)的情况而设计,因此您可以将以上内容包装在一个中:
class MessageExtensions
{
public static Message Update(this MessageUpdater updater, Dictionary<int,Message> dict, int key)
{
Message value = dict[key];
MessageUpdater.Update(ref value);
return dict[key];
}
}
那么您所要做的就是:
Message updatedMessage = myMessageUpdater.Update(myDict, key);
这样可以接受吗?
关于c# - 将引用传递给集合元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20465654/