问题描述
我想对字典中的多个变量执行 out
,如下例所示:
string color;
int number;
float numval;
Dictionary<string,(string,int,float)> Property = new Dictionary<string,float)>();
Property.Add("G",("Green",2,(float)2.99));
Property.TryGetValue("G",out(color,number,numval));
当我尝试使用 TryGetValue
时,出现此错误:
out 或 ref 值必须是可赋值的变量
我知道我可以使用一个元组,而不是像这样的多个值,但我希望它像那样工作。
解决方法
我不会在这样的字典中使用元组..但如果你真的需要,你可以这样做:
Dictionary<string,(string,int,float)> Property = new Dictionary<string,float)>();
Property.Add("G",("Green",2,2f));
if(Property.TryGetValue("G",out var val))
{
string color = val.Item1;
int number = val.Item2;
float numval = val.Item3;
// or as @canton7 suggested in the comments:
var (color,number,numVal) = val;
}