C#基礎(三):函數(方法)的定義、out、ref、params

C#是純面向對象的,和C++有點不同,比如C#的方法聲明格式如下:

[public] static 返回值類型 方法名字(參數列表)
{
    方法體
}

public 訪問修飾符,可以省略

比C++多了個修飾符,而且都得用static修飾, 靜態函數只能訪問靜態成員 。其它的和C++基本一致。

C#有類似於C++的引用傳值,用out和ref可以實現

(1)out修飾形參的用法

using System;

namespace out關鍵字
{
    class Program
    {
        //在函數形參前加out關鍵字表示該參數也會被返回,有點類似C++的引用傳值,形參可以有多個out參數
        static int testOut(int num, out string str)
        {
            str = "success";
            return num;
        }

        static void Main(string[] args)
        {
            string str;

            //參數傳到形參時也得加上out
            int ret = testOut(12, out str);

            Console.WriteLine("ret = {0}, str = {1}", ret, str);
            Console.ReadKey();
        }
    }
}

(2)ref修飾形參的用法

using System;

namespace ref關鍵字
{
    class Program
    {
        static void setMoney(ref int money)
        {
            money += 1000;
        }

        static void Main(string[] args)
        {
            int salary = 2000;

            //使用ref時,該參數必須在方法外賦值,實參前面也得用ref修飾
            setMoney(ref salary);
            Console.WriteLine("salary = " + salary);
            Console.ReadKey();
        }
    }
}

(3) params

using System;

namespace params關鍵字的使用
{
    class Program
    {
        static void Main(string[] args)
        {
            int max = getMax(12, 45, 11, 89, 6);

            Console.WriteLine("最大的數是: " + max);
            Console.ReadKey();
        }

        //params表示參數可以傳入任意個int型的數,組成數組
        //params使用的時候,函數的參數列表只有一個參數,有多個參數時只能作爲最後一個參數
        static int getMax(params int[] array)
        {
            int max = 0;
            foreach(var it in array)
            {
                if (max <= it)
                    max = it;
            }

            return max;
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章