What is the use passing Class Object using keyword “ref”? They are by by default pass by reference [duplicate]

為{幸葍}努か 提交于 2019-12-24 10:58:35

问题


I just noticed .net allows us to do like this.

  public void Func1(ref String abc)
  {
  }

I was wondering "ref" keyword makes any sense???? as String is a Class(reference type)

Is it any different from.

 public void Func1(String abc)
 {
 }

I am just asking as i am confused. either missing some concept or they are one and the same thing and "ref" keyword has no sense in this context.


回答1:


Parameters are passed by value by default. If you pass a parameter into a method, the original variable does not get modified. If you pass a parameter as a ref parameter though, the original variable that you passed in can get modified.

Try this:

public void Func1(String abc) {
    abc = "Changed from Func1";
}

public void Func2(ref String abc) {
    abc = "Changed from Func2";
}

public void main() {
    string foo = "not changed";
    Func1(foo);
    Console.WriteLine(foo);
    Func2(ref foo);
    Console.WriteLine(foo);
}

The output you will get is:

not changed
Changed from Func2

In Func1 a copy of foo is created, which refers to the same String. But as soon as you assign it another value, the parameter abc refers to another String. foo is not modified and still points to the same string.
In Func2 you pass a reference to foo, so when you assign abc a new value (i.e. a reference to another string), you are really assigning foo a new value.




回答2:


By default without the ref keyword, a copy of the string pointer is made (pass-by-value). Using ref will pass-by-reference and this also allows you to modify the pointer in the original caller.



来源:https://stackoverflow.com/questions/10276808/what-is-the-use-passing-class-object-using-keyword-ref-they-are-by-by-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!