C#函数返回多值

来源:互联网 发布:linux如何删除文件夹 编辑:程序博客网 时间:2024/04/27 20:23

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<T>

Example of Tuple:

Returning Multiple DataType values using Tuple<T>

using System;class Program{    static void Main()    {    // Create four-item tuple; use var implicit type.    var tuple = new Tuple<string, string[], int, int[]>("perl",        new string[] { "java", "c#" },        1,        new int[] { 2, 3 });    // Pass tuple as argument.    M(tuple);    }    static void M(Tuple<string, string[], int, int[]> 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

perljavac#123

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.

3) Use:

public KeyValuePair<int, int> Location(int p_1, int p_2, int p_3, int p_4){                     return new KeyValuePair<int,int>(p_2 - p_1, p_4-p_3);}

or

static Tuple<int, int> Location(int p_1, int p_2, int p_3, int p_4){    return new Tuple<int, int>(p_2 - p_1, p_4-p_3);}

4) Use custom class like Point

public class Point{    public int XLocation { get; set; }    public int YLocation { get; set; }}public static Point Location(int p_1, int p_2, int p_3, int p_4) {         return new Point      {        XLocation  = p_2 - p_1;        YLocation = p_4 - p_3;     }       }

The fastest way (best performance) is:

public KeyValuePair<int, int> Location(int p_1, int p_2, int p_3, int p_4){                     return new KeyValuePair<int,int>(p_2 - p_1, p_4-p_3);}

0 0