C#中的參數和調用方式(可選參數、具名參數、可空參數)

具名參數 和 可選參數 是 C# framework 4.0 出來的新特性。html

 

一. 常規方法定義及調用函數

複製代碼
public void Demo1(string x, int y)
{ 
      //do something...
}


public void Main()
{
      //調用
       Demo1("similar", 22);
}
複製代碼

調用時,參數順序(類型)必須與聲明一致,且不可省略。post

 

 

二. 可選參數的聲明及調用ui

可選參數分爲兩種狀況: 1. 部分參數可選;   2. 所有參數都是可選this

複製代碼
//部分可選(x爲必選,y爲可選)
public void Demo2(string x, int y = 5)
{
      //do something...
}


public void Main()
{
       //調用
       Demo2("similar");       // y不傳入實參時,y使用默認值5
       Demo2("similar", 10);   // y傳入實參,則使用實參10
}
複製代碼

注: 當參數爲部分可選時, 可選參數  的聲明必須定義在 不可選參數(命名參數)的後面(如上: y 的聲明在 x 以後),否則會出現以下錯誤提示:spa

  

複製代碼
//所有可選(x,y 均爲可選參數)
public void Demo3(string x = "demo", int y = 5)
{
       //do something...
}

public void Main()
{
       //調用
       Demo3();               // x,y不傳入實參時,x,y使用默認值 "demo",5
       Demo3("similar");      // y不傳入實參時,y使用默認值5
       Demo3("similar", 10);  // x,y都傳入實參
}
複製代碼

注: a.  當參數所有都爲可選時,參數的聲明順序能夠隨意定義,不分前後。code

        b.  參數聲明定義能夠無順序,但調用時必須與聲明時的一致。htm

上面的調用只寫的3種,其實還有一種,就是 x 使用默認值,y 傳入實參,即 :  Demo3(10);blog

但這樣調用會報錯,由於Demo3的第一個參數是 string 類型,錯誤消息如圖:ci

 

可是如今我只想傳入y, 不想傳入 x ,該怎麼辦呢,那麼就要用到 C#的 具名參數。

 

 

三. 具名參數

具名參數的使用主要是體如今函數調用的時候。

複製代碼
public void Main()
{
       //調用
       Demo3();                // x,y不傳入實參時,x,y使用默認值 "demo",5
       Demo3("similar");       // y不傳入實參時,y使用默認值5
       Demo3("similar", 10);   // x,y都傳入實參


// 具名參數的使用 Demo3(y:10); }
複製代碼

 

經過具名參數,咱們能夠指定特定參數的值,這裏咱們經過 Demo3(y:10)就能夠解決咱們上面遇到的問題(x使用默認值,y使用實參)。

注: 當使用 具名參數時,調用方法能夠不用管參數的聲明順序,即以下調用方式也是能夠的:

 

 

在調用含有可選參數的方法時,vs中會有智能提示,提示哪些是能夠選參數及其默認值,中括號表示可選[]:

 

 

出處:http://www.javashuo.com/article/p-urjhrxyf-gu.html

===================================================

可空參數是C#2中就引入的概念了,好比屬性能夠這樣定義: 

public decimal? Price { get; set; }

而方法參考能夠這樣定義:

public void GetProduct(string name, decimal? price = null)

使用:

調用屬性時,能夠直接爲Price賦值爲null

調用方法時,只傳name參數,而price則默認爲null了。

下面看看個人一個綜合應用吧!

 public DateTime? StartDate { get; set; }
 public DateTime? EndDate { get; set; }

public GetProduct(string cName = default(string), ......, ResultEnum? secResult = default(ResultEnum?), DateTime? startDate = default(DateTime?), DateTime? endTime = default(DateTime?))
{
            if (startDate == null)
            {
                throw new InvalidDataException("startDate is a required property for GetProduct and cannot be null");
            }
            else
            {
                this.StartDate = startDate;
            }
            
            // 其餘代碼邏輯
}

 

這裏的屬性使用的是可空參數,如:StartDate 和 EndDate

而構造函數這裏只列出了部分代碼,個人這個參數大概有20個左右,中間的參數省略掉了,自行腦補。而函數內部又有對startDate參數的必須提供,不然拋出異常,其餘的驗證邏輯我就不貼出來了

調用方式:

new GetProduct(startDate : DateTime.Now.AddMonths(-1), endTime : DateTime.Now)

相關文章
相關標籤/搜索