传递参数(C# 编程指南)(http://msdn.microsoft.com/zh-cn/library/0f66670z(VS.80).aspx)

在 C# 中,既可以通过值也可以通过引用传递参数。

(1).通过引用传递参数允许函数成员(方法、属性、索引器、运算符和构造函数)更改参数的值,并保持该更改。若要通过引用传递参数,请使用 refout 关键字。

(2).通过值传递值类型,通过值将变量 n 传递给方法 SquareIt。方法内发生的任何更改对变量的原始值无任何影响。

 

示例:通过值传递值类型

 

class PassingValByVal
{
    static void SquareIt(int x)
    // The parameter x is passed by value.
    // Changes to x will not affect the original value of x.
    {
        x *= x;
        System.Console.WriteLine("The value inside the method: {0}", x);
    }
    static void Main()
    {
        int n = 5;
        System.Console.WriteLine("The value before calling the method: {0}", n);
 
        SquareIt(n);  // Passing the variable by value.
        System.Console.WriteLine("The value after calling the method: {0}", n);
    }
}

 

输出:

The value before calling the method: 5

The value inside the method: 25

The value after calling the method: 5

 

示例:通过引用传递值类型

C#

复制代码

class PassingValByRef

{

    static void SquareIt(ref int x)

    // The parameter x is passed by reference.

    // Changes to x will affect the original value of x.

    {

        x *= x;

        System.Console.WriteLine("The value inside the method: {0}", x);

    }

    static void Main()

    {

        int n = 5;

        System.Console.WriteLine("The value before calling the method: {0}", n);

 

        SquareIt(ref n);  // Passing the variable by reference.

        System.Console.WriteLine("The value after calling the method: {0}", n);

    }

}

输出:

The value before calling the method: 5

The value inside the method: 25

The value after calling the method: 25

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值