close

傳值呼叫:
private void button1_Click(object sender, EventArgs e)
{
    int N = 99;
    AddNum(N); //注意,只要有變數就好
    MessageBox.Show(this, N.ToString() , "傳值呼叫");
}
private void AddNum(int M)
{
    M = M + 1;
}
傳址呼叫:
private void button1_Click(object sender, EventArgs e)
{
    int N = 99;
    AddNum(ref N); //注意,變數前面要加ref
    MessageBox.Show(this, N.ToString(), "傳參考呼叫");
}
private void AddNum(ref int M)
{
    M = M + 1;
}
傳址呼叫:不需明確初始化變數,需要明確初始化-->ref,不需要明確初始化-->out
private void btn_ref_Click(object sender, EventArgs e)
{
    double Score = 65; //需要明確初始化變數
    AddScore(ref Score);
    MessageBox.Show(this, "原分數65分,開根號乘以10後分數=" +
        Score.ToString("F2") , "ref範例");
}
public void AddScore(ref double Num)
{
    Num = Math.Sqrt(Num) * 10; //開根號乘以10
}
private void btn_out_Click(object sender, EventArgs e)
{
    string MsgStr; //不需要明確初始化變數
    GetMessage(out MsgStr);
    MessageBox.Show(this, MsgStr, "out範例");
}
public void GetMessage(out string Msg)
{
    Msg = "欠缺法律常識,只好自求多福。";
}
注意:不能多載宣告,如下,是錯誤的
public void AddMethod(out int N) { }
public void AddMethod(ref int N) { }

arrow
arrow
    全站熱搜

    羅 朝淇 發表在 痞客邦 留言(0) 人氣()