Return multiple values to a method caller

前端 未结 26 2360
故里飘歌
故里飘歌 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:33

    In C#7 There is a new Tuple syntax:

    static (string foo, int bar) GetTuple()
    {
        return ("hello", 5);
    }
    

    You can return this as a record:

    var result = GetTuple();
    var foo = result.foo
    // foo == "hello"
    

    You can also use the new deconstructor syntax:

    (string foo) = GetTuple();
    // foo == "hello"
    

    Be careful with serialisation however, all this is syntactic sugar - in the actual compiled code this will be a Tuple (as per the accepted answer) with Item1 and Item2 instead of foo and bar. That means that serialisation (or deserialisation) will use those property names instead.

    So, for serialisation declare a record class and return that instead.

    Also new in C#7 is an improved syntax for out parameters. You can now declare the out inline, which is better suited in some contexts:

    if(int.TryParse("123", out int result)) {
        // Do something with result
    }
    

    However, mostly you'll use this in .NET's own libraries, rather than in you own functions.

提交回复
热议问题