【问题标题】:How to do an out on multiple variables in a dictionary?如何对字典中的多个变量进行输出?
【发布时间】: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&lt;key, value&gt;,就像它应该的那样。您的 tryget 将起作用(因为您只有一个值),并且每个人都会理解您的代码(即使是您,在 6 个月内)。
  • @Glubus 它使用了ValueTuple,而不是Tuple——在问题的任何地方都没有提到Tuple,或者我的代码
  • @canton7 是的,你说得对,我很困惑,我的错

标签: c# dictionary variables out


【解决方案1】:

我不会在这样的字典中使用元组.. 但如果你真的需要,你可以这样做:

Dictionary<string, (string, int, float)> Property = new Dictionary<string, (string, int, 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多