C#基礎之參數(二) 數組參數、選擇性參數與具名引數

來源:互聯網
上載者:User

標籤:param   style   ram   try   strong   方法   stat   lin   str   

  這次介紹的三個參數皆屬於文法糖。

  4.數組參數

   聲明方法時,在形參前加params關鍵字。簡化了參數調用,增加了可讀性。
   用法:
   (1)在參數為數組時使用
   (2)每個方法只能有一個數組參數。且要作為最後一個參數。(只有放在最後,調用方法時編譯器才能知道哪些實參屬於數組參數)
   (3)調用方法可以將數組中的值一個個列出,而不用傳一個數組對象(當然,傳一個數組對象也是沒有錯的)。

  樣本:

 1     class Program 2     { 3         static void Main(String[] args) 4         { 5             int sum; 6             bool b = Add(out sum, 1, 2, 3, 4); 7             if (b) 8             { 9                 Console.WriteLine(sum);10             }11         }12         public static bool Add(out int sum, params int[] a)13         {14             try15             {16                 sum = 0;17                 foreach (int item in a)18                 {19                     sum += item;20                 }21                 return true;22             }23             catch (Exception)24             {25                 sum = 0;26                 return false;27             }28         }29     }

  輸出為:

10

  實際上,這時微軟為我們封裝的文法糖。編譯器會將1,2,3,4存在一個int數組中,並將數組傳遞給方法。

  5.選擇性參數

  用法:
   (1)在方發聲明時,為選擇性參數制定一個預設值。
   (2)選擇性參數的預設值必須是一個常量。
   (3)選擇性參數必須出現在所有必須參數之後,否則編譯器報錯。()
    事實上,在調用方法時,編譯器會按順序把實參依次賦值給形參,若實參的個數少於形參,則未被賦值的形參會取預設值。

   樣本:

    class Program    {        static void Main(String[] args)        {            int i = Add(4);            Console.WriteLine(i);            i = Add(1, 2);            Console.WriteLine(i);        }        public static int Add(int x, int y = 5, int z = 6)        {            return x + y + z;        }    }

  輸出為:

159

  6.具名引數

   用法:
   (1)調用方法時,顯式地說明實參所對應的實參的名字。
   (2)不必按順序輸入參數。
   (3)調用方法時,若某個參數命名,則之後的所有參數都需要命名。否則編譯器會報錯。

  具名引數的主要作用是,對於某些參數繁多的方法,可以增加代碼可讀性,避免參數順序的錯誤。

  樣本:

 1 class Program 2     { 3         static void Main(String[] args) 4         { 5             int i = Add(5, secondInt: 6); 6             Console.WriteLine(i); 7         } 8         public static int Add(int firstInt,int secondInt) 9         {10             return firstInt + secondInt;11         }12     }

 

C#基礎之參數(二) 數組參數、選擇性參數與具名引數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.