如何对字典中的多个变量进行输出?

问题描述

我想对字典中的多个变量执行 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;
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...