Return multiple values to a method caller

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

    There are several ways to do this. You can use ref parameters:

    int Foo(ref Bar bar) { }
    

    This passes a reference to the function thereby allowing the function to modify the object in the calling code's stack. While this is not technically a "returned" value it is a way to have a function do something similar. In the code above the function would return an int and (potentially) modify bar.

    Another similar approach is to use an out parameter. An out parameter is identical to a ref parameter with an additional, compiler enforced rule. This rule is that if you pass an out parameter into a function, that function is required to set its value prior to returning. Besides that rule, an out parameter works just like a ref parameter.

    The final approach (and the best in most cases) is to create a type that encapsulates both values and allow the function to return that:

    class FooBar 
    {
        public int i { get; set; }
        public Bar b { get; set; }
    }
    
    FooBar Foo(Bar bar) { }
    

    This final approach is simpler and easier to read and understand.

提交回复
热议问题