您的位置:首页 > 理论基础 > 计算机网络

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

2010-01-14 11:24 736 查看
在 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

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 编程 class
相关文章推荐