在C#中使用空值或空值初始化元组

raj*_*net 5 c# dictionary tuples trygetvalue

我有这个字典和元组在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)
}
Run Code Online (Sandbox Code Playgroud)

我试图在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;
   }
}
Run Code Online (Sandbox Code Playgroud)

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

 var myTuple = new Tuple<string, string>("","");
Run Code Online (Sandbox Code Playgroud)

fsi*_*zzi 16

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

Tuple<string, string> myTyple;
Run Code Online (Sandbox Code Playgroud)


Dav*_*ych 15

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

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