【问题标题】:Initialize tuple with empty or null values in C#在 C# 中使用空值或空值初始化元组
【发布时间】:2012-11-10 04:49:56
【问题描述】:

我在 SetValue() 中设置了这个字典和元组,如下所示:-

var myDict = new Dictionary<string, Tuple<string, string>>();

private void SetValue() 
{
  var myTuple1= Tuple.Create("ABC", "123");
  var myTuple2= Tuple.Create("DEF", "456");
  myDict.Add("One", myTuple1)
  myDict.Add("Two", myTuple2)
}

我正在尝试检索 GetValue() 中的元组,如下所示:-

private void GetValue()
{
  var myTuple = new Tuple<string, string>("",""); //Is this correct way to initialize   tuple
  if (myDict.TryGetValue(sdsId, out myTuple))
  {
    var x = myTuple.Item1;
    var y = myTuple.Item2;
   }
}

我的问题是,这是否是在从字典中检索元组时初始化元组的正确方法?有更好的代码吗?

 var myTuple = new Tuple<string, string>("","");

【问题讨论】:

  • 初始化元组与使用字典没有直接关系。这两个类不相关。

标签: c# dictionary tuples trygetvalue


【解决方案1】:

您不需要为 out 参数创建实例。只需将局部变量声明为元组,但不要赋值。

Tuple<string, string> myTyple;

【讨论】:

  • @TimSchmelter 我诚实地阅读了这个问题,要求以最佳方式定义在该场景中使用的变量。因此,它只需要声明即可。
【解决方案2】:

如果是out参数,对象在使用前不需要初始化。你应该能够做到:

Tuple<string,string> myTuple;
if (myDict.TryGetValue(sdsId, out myTuple))
{
    var x = myTuple.Item1;
    var y = myTuple.Item2;
}

【讨论】:

  • 确实如此。我肯定是个笨蛋。谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多