究竟什么是包含ref修饰符的参数?

时间:2017-06-09 13:51:07

标签: c# methods parameters ref

我想问一下ref修饰符。

我所了解和理解的事情: 使用ref修饰符的方法,没有像传递值那样的数据副本,但参数将直接访问参数值。基本上说,你在方法范围内所做的所有操作都与在调用者范围内使用参数(传递变量)一样。

我想问一下使用ref修饰符确切存储在参数中的内容: 当我使用ref修饰符将参数传递给方法时,参数是否包含对参数值的引用?还是别的什么?

感谢您的回答

2 个答案:

答案 0 :(得分:1)

如果您有一个带有ref属性的参数,它会通过引用传递参数而不是值。这意味着没有制作变量的新副本,而是在您的函数中使用了指向原始的指针。

public void Foo()
    {
        var x = 0;
        Bar(x); // x still equals 0
        Bar(ref x); // x now equals 1
    }

    public void Bar(ref int x)
    {
        x = 1;
    }

    public void Bar(int x)
    {
        x = 1;
    }

答案 1 :(得分:1)

我们说我们有这种方法:

public static void main(String[] args) {

    int[] A=new int[size];
      //code for take input in array
      int[] C=sorting(A); //pass array via method
      //and then print array

    }
public static int[] sorting(int[] a) {
     //code for work with array 
     return a; //retuen array
}

我们使用它:

public void DoSomething(int number)
{
    number = 20;
}

输出为var number = 10; DoSomething(number); Console.WriteLine("Our number is: {0}", number); 。我们的号码不会变成20。

因为我们通过值,所以我们在更改之前基本上会复制Our number is: 10

但是,如果我们通过引用传递

number

然后使用我们的方法:

public void DoSomething(ref int number)
{
    number = 20;
}

然后输出变为var number = 10; DoSomething(ref number); Console.WriteLine("Our number is: {0}", number);