Return multiple values to a method caller

前端 未结 26 2329
故里飘歌
故里飘歌 2020-11-21 21:57

I read the C++ version of this question but didn\'t really understand it.

Can someone please explain clearly if it can be done and how?

相关标签:
26条回答
  • 2020-11-21 22:58

    Some answers suggest using out parameters but I recommend not using this due to they don’t work with async methods. See this for more information.

    Other answers stated using Tuple, which I would recommend too but using the new feature introduced in C# 7.0.

    (string, string, string) LookupName(long id) // tuple return type
    {
        ... // retrieve first, middle and last from data storage
        return (first, middle, last); // tuple literal
    }
    
    var names = LookupName(id);
    WriteLine($"found {names.Item1} {names.Item3}.");
    

    Further information can be found here.

    0 讨论(0)
  • 2020-11-21 22:58

    you can try this "KeyValuePair"

    private KeyValuePair<int, int> GetNumbers()
    {
      return new KeyValuePair<int, int>(1, 2);
    }
    
    
    var numbers = GetNumbers();
    
    Console.WriteLine("Output : {0}, {1}",numbers.Key, numbers.Value);
    

    Output :

    Output : 1, 2

    0 讨论(0)
提交回复
热议问题