程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#函數參數傳送之out與ref的應用

C#函數參數傳送之out與ref的應用

編輯:C#入門知識

下面我總結下我對out和ref引用參數的看法:
              1.out和ref引用參數的相同點:都是通過引用傳遞參數給函數;
              2.out和ref引用參數的不同點是:用ref引用傳遞參數,該參數必須經過初始化,並且不能在調用它的函數中初始化,以下例子是錯誤的:
                              namespace refConsoleApp
                                 {
                                      class MyRefClass
                                         {
                                                static void MyRefMethod(ref int i)
                                                   {
                                                                 int i=20;
                                                   }
                                                  static void main(string[] args)
                                                  {
                                                          int value;                  //not initialized the value;
                                                          MyRefMethod(ref value);
                                                          Console.WriteLine("The value is {0}",value);
                                                  }
                             }
                               }
                 3.使用out引用多個參數來返回多個值,這允許方法任意地返回需要的值,以下例子:
namespace multi_outConsoleApp
{
    class MyMultipleoutClass
    {
        static void MyMultipleMethod(out int i, out string str1, out string str2)
        {
            i = 20;
            str1 = "I was born";
            str2 = "zhaoqing";

        }
        static void Main(string[] args)
        {
            int value;
            string s1, s2;
            MyMultipleMethod(out value,out  s1,out  s2);
            Console.WriteLine("The integer value is {0} The first string value is {1} The second string value is {2}", value, s1, s2);

        }
    }
}

顯示的結果為:
The integer value is 20
The first string value is I was born
The second string value is zhaoqing
      4.  如果一個方法使用ref引用參數,另一個方法使用out引用參數,則這兩個相同方法名的函數不能重載,否則出現編譯錯誤,以下例子出現: " cannot define overloaded  methods that differ only on ref and out "
namespace overloadofConsoleApp
{
    class overloadofclass
    {
        static void MyMethod(ref int i)
        {
            i = 20;
        }
        static void MyMethod(out int i)
        {
          i = 40;
        }
        static void Main(string[] args)
        {
            int refvalue=0;
            MyMethod(ref refvalue);
            Console.WriteLine("The value is {0}", refvalue);
   &

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved