Return multiple values to a method caller

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

    No, you can't return multiple values from a function in C# (for versions lower than C# 7), at least not in the way you can do it in Python.

    However, there are a couple alternatives:

    You can return an array of type object with the multiple values you want in it.

    private object[] DoSomething()
    {
        return new [] { 'value1', 'value2', 3 };
    }
    

    You can use out parameters.

    private string DoSomething(out string outparam1, out int outparam2)
    {
        outparam1 = 'value2';
        outparam2 = 3;
        return 'value1';
    }
    
    0 讨论(0)
  • 2020-11-21 22:47

    Previous poster is right. You cannot return multiple values from a C# method. However, you do have a couple of options:

    • Return a structure that contains multiple members
    • Return an instance of a class
    • Use output parameters (using the out or ref keywords)
    • Use a dictionary or key-value pair as output

    The pros and cons here are often hard to figure out. If you return a structure, make sure it's small because structs are value type and passed on the stack. If you return an instance of a class, there are some design patterns here that you might want to use to avoid causing problems - members of classes can be modified because C# passes objects by reference (you don't have ByVal like you did in VB).

    Finally you can use output parameters but I would limit the use of this to scenarios when you only have a couple (like 3 or less) of parameters - otherwise things get ugly and hard to maintain. Also, the use of output parameters can be an inhibitor to agility because your method signature will have to change every time you need to add something to the return value whereas returning a struct or class instance you can add members without modifying the method signature.

    From an architectural standpoint I would recommend against using key-value pairs or dictionaries. I find this style of coding requires "secret knowledge" in code that consumes the method. It must know ahead of time what the keys are going to be and what the values mean and if the developer working on the internal implementation changes the way the dictionary or KVP is created, it could easily create a failure cascade throughout the entire application.

    0 讨论(0)
  • 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.

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

    Classes, Structures, Collections and Arrays can contain multiple values. Output and reference parameters can also be set in a function. Return multiple values is possible in dynamic and functional languages by means of tuples, but not in C#.

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

    Future version of C# is going to include named tuples. Have a look at this channel9 session for the demo https://channel9.msdn.com/Events/Build/2016/B889

    Skip to 13:00 for the tuple stuff. This will allow stuff like:

    (int sum, int count) Tally(IEnumerable<int> list)
    {
    // calculate stuff here
    return (0,0)
    }
    
    int resultsum = Tally(numbers).sum
    

    (incomplete example from video)

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

    you can try this

    public IEnumerable<string> Get()
     {
         return new string[] { "value1", "value2" };
     }
    
    0 讨论(0)
提交回复
热议问题