Method with Multiple Return Types

前端 未结 3 1051
梦如初夏
梦如初夏 2021-02-14 07:57

I\'ve looked through many questions that are similar to this, but none of them really touched on what I precisely want to do. What I am trying to do is read from an external sou

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-14 08:23

    In C# 7 you have the option to return multiple values from a method like this:

    public (string SomeString, int SomeInt) DoSomething() {... }
    

    You can get the values like this:

    var result = DoSomething();
    Console.WriteLine(result.SomeString);
    Console.WriteLine(result.SomeInt.ToString());
    

    Or

    (var someString, var someInt) = DoSomething();
    Console.WriteLine(someString);
    Console.WriteLine(someInt.ToString());
    

    This works below the surface with a Tuple and you are not restricted to only 2 values. I don't know how many you can return but I suggest when you need to return that many values, create a class. More info: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

提交回复
热议问题