c#關鍵字,ref和out

來源:互聯網
上載者:User

    最近在寫程式時遇到ref,out 參數問題。回頭有自習看了看MSDN,才有鞏固了基礎。我把我的測試程式貼出來,大家分享一下。
    ref 關鍵字使參數按引用傳遞。其效果是,當控制權傳遞迴調用方法時,在方法中對參數的任何更改都將反映在該變數中。若要使用 ref 參數,則方法定義和調用方法都必須顯式使用 ref 關鍵字。傳遞到 ref 參數的參數必須最先初始化。這與 out 不同,後者的參數在傳遞之前不需要顯式初始化。這是out與ref的卻別所在。
     有點像,c++中的函數傳遞引用,和傳遞值。比較經典的程式是交換兩個數。這裡不在貼出代碼。

代碼

using System;
using System.Collections.Generic;

public class MyClass
{
 public static void Main()
 {
 
  /// 通過測試發現,基底類型的參數,在沒有用ref 的聲明後,其值並沒有改變,說明此函數中傳遞的是值。
  /// 但是,當使用ref 參數是發現,其值發生了變化,說明在此函數中傳遞的是引用。
  int x=100;
  ChangeTheNumber(ref x);
  Console.WriteLine(x.ToString());
  
  
  ///通過測試發現,類的執行個體作為,參數,即使不用ref 參數,它的屬性也發生了變化。那是因為,類的的執行個體,是一個引用。所以不用再使用ref了。
  /// 這讓我想到了,幾個月前的項目開發,在不同表單之間傳遞參數,但是一直想著做個什麼共有方法,然後互相調用。但是,其實很簡單,
  /// 在建構函式中傳入需要傳入的類的執行個體就可以了,因為傳遞的是引用。其屬性都會變化。不用再用什麼麻煩的方法了。
  ///TestTheClass
     TestClass classInstance1=new TestClass("firstname");
  ChangeTheNumber(classInstance1);
  Console.WriteLine(classInstance1.Name);
  
  TestClass classInstance2=new TestClass("second");
  ChangeTheNumber(classInstance2);
  Console.WriteLine(classInstance2.Name);
  Console.Read();
 }
 
 #region Helper methods

 private static void WL(object text, params object[] args)
 {
  Console.WriteLine(text.ToString(), args); 
 }
 
 private static void RL()
 {
  Console.ReadLine(); 
 }
 
 private static void Break() 
 {
  System.Diagnostics.Debugger.Break();
 }

    private static void ChangeTheNumber(ref int number)
 {
  number=100;
 }
 
 private static void ChangeTheNumber(int x)
 {
  x=100;
 }
 
 private static void ChangeTheNumber(TestClass classInstance)
 {
  classInstance.Name="change to another name";
 }
 
 private static void ChangeTheNumber(ref TestClass classInstance)
 {
  classInstance.Name="change to another name";
 }
 #endregion
}

///
///測試類別
///
public class TestClass
{
 public TestClass(string name)
 {
  this.name=name;
 }
 
 private string name;
 public string Name
 {
  get
  {
   return name;
  }
  set
  {
   name=value;
  }
 }
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.