Return multiple values to a method caller

前端 未结 26 2334
故里飘歌
故里飘歌 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 22:31

    Now that C# 7 has been released, you can use the new included Tuples syntax

    (string, string, string) LookupName(long id) // tuple return type
    {
        ... // retrieve first, middle and last from data storage
        return (first, middle, last); // tuple literal
    }
    

    which could then be used like this:

    var names = LookupName(id);
    WriteLine($"found {names.Item1} {names.Item3}.");
    

    You can also provide names to your elements (so they are not "Item1", "Item2" etc). You can do it by adding a name to the signature or the return methods:

    (string first, string middle, string last) LookupName(long id) // tuple elements have names
    

    or

    return (first: first, middle: middle, last: last); // named tuple elements in a literal
    

    They can also be deconstructed, which is a pretty nice new feature:

    (string first, string middle, string last) = LookupName(id1); // deconstructing declaration
    

    Check out this link to see more examples on what can be done :)

提交回复
热议问题