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,

相关文章
相关标签/搜索