C#参数传递机制

  C#方法的参数传递机制和C语言、C++语言不一样的是,新增加了一种叫做输出传递机制,其他两种机制为值传递和引用传递机制。

  总结如下:

  C#方法的参数传递机制有以下三种方法:

 

  1. 值传递
  2. 引用传递
  3. 输出传递

 

 根据以上描述,我们来举个例子说明这三种传递机制内幕。

 


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);
        }
    }
}

 

   使用这三种传递机制的时候,要注意的问题都在注释中给出。程序输出的结果为:

 i = 0

j = 1

k = 1

  那么,回顾以下,可以发现,在C#中,Main函数的局部变量如果使用值传递的办法,那么该参数被调用后,依然保持调用前的值。而输出参数和引用参数都会改变被引用的变量值。

 

下面来讲讲可变长参数 的传递(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,

 

转载于:https://www.cnblogs.com/ktyanny/archive/2010/05/19/1739505.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值