.
在 C# 中指標包裝起來,不像C或C++可以直接使用,在C# MSDN的說明中指出
雖然有支援指標功能,但不建議使用,如果發生問題自行負責
指標本來就是不安全的用法,如果隨意使用確實很容易出問題
有上述可見,C#中正常是不會出現指標的用法
但有很多資料結構已經把指標封裝起來,意思就是底層已經被實作
程式撰寫者只需調用該物件即可自行編成邏輯使用
其中 Call By Reference 如同字面上的意思,用位址傳值
當原始位址的值改變,參數的值也會跟著改變
以下範例舉例使用C# 的 out 跟 ref 來演示 Call By Reference
Class Main
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
-
- namespace out_ref_test
- {
- public partial class Form1 : Form
- {
- int[] array = { 1, 2, 3, 4, 5 };
- int num1 = 999, num2 = 999;
- float fnum1 = 0, fnum2 = 0;
- ModifyArray modArr = new ModifyArray();
-
- public Form1()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- modArr.chage_array(array);
- modArr.chage_int(ref num1, ref num2);
- modArr.chage_float(out fnum1, out fnum2);
-
- for(int i = 0; i < array.Length ; i++)
- {
- if (i == array.Length - 1)
- {
- textBox1.Text += array[i];
- }
- else
- {
- textBox1.Text += array[i] + ", ";
- }
- }
-
- textBox2.Text += num1 + ", " + num2;
-
- textBox3.Text += fnum1 + ", " + fnum2;
- }
- }
- }
Class Modify
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace out_ref_test
- {
- public class Modify
- {
- public void chage_array(int[] arr)
- {
- arr[2] = 222;
- arr[3] = 999;
- }
-
- public void chage_int(ref int a, ref int b)
- {
- a = 100; //如果不初始化則 a++ 不會被執行
- b = 200;
- a ++;
- b ++;
- /*a = 100;
- b = 200;*/
- }
-
- public void chage_float(out float a, out float b)
- {
- a = 100.11f;
- b = 200.22f;
- }
- }
- }
上述範例主要使用三種方式呈現 Call By Reference
第一個是使用陣列,從結果可以看出陣列本身就已經是 Call By Reference
將陣列傳入 Class後改變數值不需回傳,在主程式執行的結果仍會改變
第二和三為使用 ref和 out 來實現在副程式中回傳多個值的用法
ref 和 out 不同的地方為 ref使用前需先初始化,否則會無法正常運作