C#參數傳遞機制

C#方法的參數傳遞機制和C語言、C++語言不同的是,新增長了一種叫作輸出傳遞機制,其餘兩種機制爲值傳遞和引用傳遞機制。函數

  總結以下:spa

  C#方法的參數傳遞機制有如下三種方法:code

 

  1. 值傳遞
  2. 引用傳遞
  3. 輸出傳遞

 

 根據以上描述,咱們來舉個例子說明這三種傳遞機制內幕。blog


using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;

namespace  Method
{
    
class  Program
    {
        
public   static   void  ValueMethod( int  i) // 值傳遞
        {
            i
++ ;
        }
        
public   static   void  RefereceMethod( ref   int  i) // 參數傳遞
        {
            i
++ ;
        }
        
public   static   void  OutMethod( out   int  i) // 輸出傳遞
        {
            i 
=   0 ;
            i
++ ;
        }
        
static   void  Main( string [] args)
        {
            
int  i  =   0 ;
            ValueMethod(i);
            Console.WriteLine(
" i =  "   +  i);
            
int  j  =   0 ;
            RefereceMethod(
ref  j); // 此處必定要添加ref傳入
            Console.WriteLine( " j =  "   + j);
            
int  k  =   0 ;
            OutMethod(
out  k);
            Console.WriteLine(
" k =  "   +  k);
        }
    }
}

 

   使用這三種傳遞機制的時候,要注意的問題都在註釋中給出。程序輸出的結果爲:ip

 i = 0string

j = 1it

k = 1io

  那麼,回顧如下,能夠發現,在C#中,Main函數的局部變量若是使用值傳遞的辦法,那麼該參數被調用後,依然保持調用前的值。而輸出參數和引用參數都會改變被引用的變量值。class

 

下面來說講可變長參數 的傳遞(params)先看代碼:變量

using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;

namespace  Method
{
    
class  Program
    {
        
static   int  addi( params   int [] values)
        {
            
int  sum  =   0 ;
            
foreach  ( int  i  in  values)
                sum 
+=  i;
            
return  sum;
        }
        
static   void  PrintArr( int [] arr)
        {
            
for  ( int  i  =   0 ; i  <  arr.Length; i ++ )
                arr[i] 
=  i;
        }
        
static   void  Main( string [] args)
        {
            
int [] arr  =  {  100 200 300 400  };
            PrintArr(arr);
            
foreach  ( int  i  in  arr)
                Console.Write(i 
+   " " );
            Console.WriteLine();
        }
    }
}

 

 

 輸出的結果爲: 0, 1, 2, 3,

相關文章
相關標籤/搜索