什么是使用关键字和QUOT利用传球类对象;参考"?它们是默认通过引用传递关键字、对象、QUOT

2023-09-06 17:50:13 作者:撩妹一把手

我只注意到.NET允许我们做这样的。

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

  public void Func1(ref String abc)
  {
  }

我在想,裁判的文章让任何意义????因为String是一个类(引用类型)

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

这是任何不同。

 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.

推荐答案

参数由值通过默认。如果您传递参数给方法,原来的变量不被修改。如果你传递一个参数作为 REF 参数虽然,你通过在原来的变量可以被修改。

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.

试试这个:

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

FUNC1 的副本创建的,它指的是相同的字符串。但只要你为它指定另一个值,参数农行引用另一个字符串。 不被修改,并仍然指向相同的字符串。 在 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.