我已经在 C# 中创建了一个泛型集合的实例,并且需要通过引用一个方法来传递该集合中结构的成员之一。我可以使用通用集合的索引器来选择我想在方法中修改的对象成员吗?我似乎得到一个错误(“无法修改‘表达式’的返回值,因为它不是一个变量”)但我所拥有的与此类似:
Deque<Card> deck_of_cards = new Deque<Card>(); // standard deck of 52 playing cards (structs)
ModifyRank( ref deck_of_cards[4].rank, 8); // Changes the rank (field, int) of the 5th card to 8
我正在转换使用 std::deque 和全局方法的 C++ 代码,我想尽可能多地保留语法。有谁知道这个问题的优雅解决方案?
请您参考如下方法:
不可能通过引用传递通过索引器获得的结构的字段。要修改此类集合中结构的内容,需要单独的获取和设置操作,因为索引器不能通过引用返回值(至少在 C# 中不能——对于无法验证的 MSIL 可能是这样)。
针对特定问题最直接的解决方案是:
Deque<Card> deck_of_cards = new Deque<Card>(); // standard deck of 52 playing cards
var tmp = deck_of_cards[4];
ModifyRank( ref tmp.rank, 8); // Changes the rank (int) of the 5th card to 8
deck_of_cards[4] = tmp;
