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 = { 100200300400 };
            PrintArr(arr);
            
foreach (int i in arr)
                Console.Write(i 
+ "");
            Console.WriteLine();
        }
    }
}

 

 

 输出的结果为: 0, 1, 2, 3,

 

posted on 2010-05-19 19:09  Ktyanny Home  阅读(410)  评论(0编辑  收藏  举报

导航