標籤

2018年3月18日 星期日

C# - Function傳值和傳址的小測試

᳓重點整理
這是function透過傳值和傳址兩種方式傳入參數的小測試。傳值是只將function的參數值,設定成與輸入變數的值相同;而傳址則是直接將輸入變數作為function的參數使用,因此會造就以下幾點不同:

  • 以傳值方式傳入的參數,在function中修改參數值也不會影響到輸入變數。
  • 以傳址方式傳入的參數,在function中修改參數值會影響到輸入變數。
  • 傳值跟傳址的function即使同名也視為不同的function,可正確執行。


᳓實作1. 建立專案
建立一個Windows Forms Application專案,並在Form拉入兩個Label、兩個Button。

᳓實作2. 修改FunctionRefTest.cs
加入兩個Button_Click事件、兩個function,並輸入以下程式碼,測試重點為在function中會修改參數值,並於function執行完畢後輸出變數值。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication_FunctionRefTest
{
public partial class FunctionRefTest : Form
{
public FunctionRefTest()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int r = 4;
double result = CalculateArea(r);
MessageBox.Show("傳值: " + r + " " + result); // "傳值: 4 16"
}
static double CalculateArea(int r)
{
double Volume = r * r;
r = r + 1;
return Volume;
}
private void button2_Click(object sender, EventArgs e)
{
int p = 4;
double result = CalculateArea(ref p);
MessageBox.Show("傳址: " + p + " " + result); // "傳址: 5 16"
}
static double CalculateArea(ref int p)
{
double Volume = p * p;
p = p + 1;
return Volume;
}
}
}

傳值測試:輸入變數值為4,輸出時不變。

傳址測試:輸入變數值為4,輸出時已被修改。

沒有留言:

張貼留言