Return multiple values to a method caller

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

    Here are basic Two methods:

    1) Use of 'out' as parameter You can use 'out' for both 4.0 and minor versions too.

    Example of 'out':

    using System;
    
    namespace out_parameter
    {
      class Program
       {
         //Accept two input parameter and returns two out value
         public static void rect(int len, int width, out int area, out int perimeter)
          {
            area = len * width;
            perimeter = 2 * (len + width);
          }
         static void Main(string[] args)
          {
            int area, perimeter;
            // passing two parameter and getting two returning value
            Program.rect(5, 4, out area, out perimeter);
            Console.WriteLine("Area of Rectangle is {0}\t",area);
            Console.WriteLine("Perimeter of Rectangle is {0}\t", perimeter);
            Console.ReadLine();
          }
       }
    }
    

    Output:

    Area of Rectangle is 20

    Perimeter of Rectangle is 18

    *Note:*The out-keyword describes parameters whose actual variable locations are copied onto the stack of the called method, where those same locations can be rewritten. This means that the calling method will access the changed parameter.

    2) Tuple

    Example of Tuple:

    Returning Multiple DataType values using Tuple

    using System;
    
    class Program
    {
        static void Main()
        {
        // Create four-item tuple; use var implicit type.
        var tuple = new Tuple("perl",
            new string[] { "java", "c#" },
            1,
            new int[] { 2, 3 });
        // Pass tuple as argument.
        M(tuple);
        }
    
        static void M(Tuple tuple)
        {
        // Evaluate the tuple's items.
        Console.WriteLine(tuple.Item1);
        foreach (string value in tuple.Item2)
        {
            Console.WriteLine(value);
        }
        Console.WriteLine(tuple.Item3);
        foreach (int value in tuple.Item4)
        {
            Console.WriteLine(value);
        }
        }
    }
    

    Output

    perl
    java
    c#
    1
    2
    3
    

    NOTE: Use of Tuple is valid from Framework 4.0 and above.Tuple type is a class. It will be allocated in a separate location on the managed heap in memory. Once you create the Tuple, you cannot change the values of its fields. This makes the Tuple more like a struct.

提交回复
热议问题