【发布时间】:2021-03-23 09:17:29
【问题描述】:
我想对字典中的多个变量执行out,如下例所示:
string color;
int number;
float numval;
Dictionary<string, (string, int, float)> Property = new Dictionary<string, (string, int, float)>();
Property.Add("G", ("Green", 2, (float)2.99));
Property.TryGetValue("G", out(color, number, numval));
当我尝试使用TryGetValue 时,我得到了这个错误:
out 或 ref 值必须是可赋值变量
我知道我可以使用一个元组,而不是像这样使用多个值,但我希望它像那样工作。
【问题讨论】:
-
这还不被支持,see the discussion here。你能做的最好的就是
TryGetValue("G", out var value); var (color, number, numval) = value; -
将你的值移动到一个类中,然后你的字典就会变成
Dictionary<key, value>,就像它应该的那样。您的tryget将起作用(因为您只有一个值),并且每个人都会理解您的代码(即使是您,在 6 个月内)。 -
@Glubus 它使用了
ValueTuple,而不是Tuple——在问题的任何地方都没有提到Tuple,或者我的代码 -
@canton7 是的,你说得对,我很困惑,我的错
标签: c# dictionary variables out