1. 程式人生 > 其它 >C# 呼叫一個函式通過out返回多個變數值/資料

C# 呼叫一個函式通過out返回多個變數值/資料

技術標籤:c#c#

我們知道一個函式使用過Return來返回值的話只能返回一個值,在c#中,自定義一個函式時,用out 來out多個值出來,呼叫的時候就可以返回多個值

舉例:

現在自己寫一個函式calculate(),需要返回加法和減法的計算結果,在主函式中輸出

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int c , d ;
            calculate(2, 3, out c,out d);
            Console.WriteLine(c);
            Console.WriteLine(d);
            Console.ReadLine();
            
        }

        private static void calculate(int a, int b, out int c, out int d)

        {
            c = a + b;
            d = a - b;


        }
    }
}

private 寫習慣了

static 不想在主函式中再對calculate例項化

void 不要返回值 (第一次寫的時候掉了void 別掉)

也可以加返回值,比如,取返回值是bool型。比較a,b的值,如果a>b,輸出c,如果a<=b,則c不輸出,輸出“nothing”

        static void Main(string[] args)
        {
            int c;
            if (calculate(2, 3, out c))
                Console.WriteLine("c = "+c);
            else
                Console.WriteLine("Nothing");
            Console.ReadLine();
            
        }

        private static bool calculate(int a, int b, out int c)

        {
            bool t;
            if (a > b)
                t = true;
            else
                t = false;
            c = a - b;
            return t;

        }

輸出結果:

如果改變輸入 使得a= 3,b =2,則輸出結果: