close

我們在寫程式時難免要傳陣列參數到Method裡面,範例是做一個數字的加總

public int Sum(params int[] values)
{
	int result = 0;

	foreach (int item in values)
	{
		result += item;
	}

	return result;
}

需要注意的是參數陣列params必須是最後一個參數

呼叫的方法很簡單

int[] total = { 1, 2, 3 };
Label1.Text = Sum(total); //result=6
Label1.Text = Sum(4, 5, 6); //result=15
Label1.Text = Sum(); //result=0

傳進去的參數可以是陣列也可以直接傳進去也可以不傳

這可以應用在需要傳入不固定的參數,例如要清空網頁上控制項的值

public void ClearControl(params Control[] controls)
{
	foreach (Control item in controls)
	{
		if (item is TextBox)
		{
			(item as TextBox).Text = string.Empty;
		}
		else if (item is Label)
		{
			(item as Label).Text = string.Empty;
		}
	}
}

清空只需要一行即可

ClearControl(TextBox1, TextBox2, TextBox3, Label1);
arrow
arrow

    Leo 發表在 痞客邦 留言(0) 人氣()