Return multiple values to a method caller

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

    You can use three different ways

    1. ref / out parameters

    using ref:

    static void Main(string[] args)
    {
        int a = 10;
        int b = 20;
        int add = 0;
        int multiply = 0;
        Add_Multiply(a, b, ref add, ref multiply);
        Console.WriteLine(add);
        Console.WriteLine(multiply);
    }
    
    private static void Add_Multiply(int a, int b, ref int add, ref int multiply)
    {
        add = a + b;
        multiply = a * b;
    }
    

    using out:

    static void Main(string[] args)
    {
        int a = 10;
        int b = 20;
        int add;
        int multiply;
        Add_Multiply(a, b, out add, out multiply);
        Console.WriteLine(add);
        Console.WriteLine(multiply);
    }
    
    private static void Add_Multiply(int a, int b, out int add, out int multiply)
    {
        add = a + b;
        multiply = a * b;
    }
    

    2. struct / class

    using struct:

    struct Result
    {
        public int add;
        public int multiply;
    }
    static void Main(string[] args)
    {
        int a = 10;
        int b = 20;
        var result = Add_Multiply(a, b);
        Console.WriteLine(result.add);
        Console.WriteLine(result.multiply);
    }
    
    private static Result Add_Multiply(int a, int b)
    {
        var result = new Result
        {
            add = a * b,
            multiply = a + b
        };
        return result;
    }
    

    using class:

    class Result
    {
        public int add;
        public int multiply;
    }
    static void Main(string[] args)
    {
        int a = 10;
        int b = 20;
        var result = Add_Multiply(a, b);
        Console.WriteLine(result.add);
        Console.WriteLine(result.multiply);
    }
    
    private static Result Add_Multiply(int a, int b)
    {
        var result = new Result
        {
            add = a * b,
            multiply = a + b
        };
        return result;
    }
    

    3. Tuple

    Tuple class

    static void Main(string[] args)
    {
        int a = 10;
        int b = 20;
        var result = Add_Multiply(a, b);
        Console.WriteLine(result.Item1);
        Console.WriteLine(result.Item2);
    }
    
    private static Tuple Add_Multiply(int a, int b)
    {
        var tuple = new Tuple(a + b, a * b);
        return tuple;
    }
    

    C# 7 Tuples

    static void Main(string[] args)
    {
        int a = 10;
        int b = 20;
        (int a_plus_b, int a_mult_b) = Add_Multiply(a, b);
        Console.WriteLine(a_plus_b);
        Console.WriteLine(a_mult_b);
    }
    
    private static (int a_plus_b, int a_mult_b) Add_Multiply(int a, int b)
    {
        return(a + b, a * b);
    }
    

提交回复
热议问题