我正在创建一个函数,我需要传递一个对象,以便它可以被函数修改。有什么区别:
public void myFunction(ref MyClass someClass)
and
public void myFunction(out MyClass someClass)
我应该用哪个,为什么?
我正在创建一个函数,我需要传递一个对象,以便它可以被函数修改。有什么区别:
public void myFunction(ref MyClass someClass)
and
public void myFunction(out MyClass someClass)
我应该用哪个,为什么?
当前回答
它们几乎是一样的——唯一的区别是,作为out形参传递的变量不需要初始化,使用ref形参的方法必须将其设置为某个值。
int x; Foo(out x); // OK
int y; Foo(ref y); // Error
Ref形参用于可能被修改的数据,out形参用于已经使用返回值的函数(例如int.TryParse)的额外输出数据。
其他回答
ref修饰符的意思是:
该值已经设置,并且 该方法可以读取和修改它。
out修饰符的意思是:
Value未被设置,并且在设置之前不能被方法读取。 方法必须在返回之前设置它。
“贝克”
这是因为第一个将字符串引用更改为指向“Baker”。更改引用是可能的,因为您通过ref关键字传递了它(=>是对字符串引用的引用)。 第二个调用获取字符串引用的副本。
弦一开始看起来很特别。但字符串只是一个引用类,如果你定义
string s = "Able";
那么s是一个包含文本“Able”的字符串类的引用! 对同一个变量via的另一个赋值
s = "Baker";
不改变原来的字符串,但只是创建一个新的实例,让我们指向该实例!
你可以试试下面的小代码示例:
string s = "Able";
string s2 = s;
s = "Baker";
Console.WriteLine(s2);
你想要什么? 您将得到的仍然是“Able”,因为您只是将s中的引用设置为另一个实例,而s2指向原始实例。
编辑: String也是不可变的,这意味着根本没有修改现有字符串实例的方法或属性(你可以尝试在文档中找到一个,但你找不到:-))。所有字符串操作方法都会返回一个新的字符串实例!(这就是为什么你在使用StringBuilder类时经常会得到更好的性能)
对于那些以身作则的人(比如我),以下是安东尼·科索夫所说的。
我创建了一些ref、out和其他例子来说明这一点。我并没有介绍最佳实践,只是举例来理解它们之间的差异。
https://gist.github.com/2upmedia/6d98a57b68d849ee7091
假设多姆因为TPS报告的备忘录出现在彼得的隔间里。
如果Dom是一个参考参数,他就会有一份备忘录的打印副本。
如果多姆是一个多余的论据,他会让彼得打印一份新的备忘录,让他随身携带。
为了说明这些优秀的解释,我开发了以下控制台应用程序:
using System;
using System.Collections.Generic;
namespace CSharpDemos
{
class Program
{
static void Main(string[] args)
{
List<string> StringList = new List<string> { "Hello" };
List<string> StringListRef = new List<string> { "Hallo" };
AppendWorld(StringList);
Console.WriteLine(StringList[0] + StringList[1]);
HalloWelt(ref StringListRef);
Console.WriteLine(StringListRef[0] + StringListRef[1]);
CiaoMondo(out List<string> StringListOut);
Console.WriteLine(StringListOut[0] + StringListOut[1]);
}
static void AppendWorld(List<string> LiStri)
{
LiStri.Add(" World!");
LiStri = new List<string> { "¡Hola", " Mundo!" };
Console.WriteLine(LiStri[0] + LiStri[1]);
}
static void HalloWelt(ref List<string> LiStriRef)
{ LiStriRef = new List<string> { LiStriRef[0], " Welt!" }; }
static void CiaoMondo(out List<string> LiStriOut)
{ LiStriOut = new List<string> { "Ciao", " Mondo!" }; }
}
}
/*Output:
¡Hola Mundo!
Hello World!
Hallo Welt!
Ciao Mondo!
*/
AppendWorld: A copy of StringList named LiStri is passed. At the start of the method, this copy references the original list and therefore can be used to modify this list. Later LiStri references another List<string> object inside the method which doesn't affect the original list. HalloWelt: LiStriRef is an alias of the already initialized ListStringRef. The passed List<string> object is used to initialize a new one, therefore ref was necessary. CiaoMondo: LiStriOut is an alias of ListStringOut and must be initialized.
因此,如果一个方法只是修改了被传递的变量引用的对象,编译器不会让你使用out,你也不应该使用ref,因为它不仅会让编译器困惑,而且会让代码的读者困惑。如果该方法将使传递的参数引用另一个对象,则对于已经初始化的对象使用ref,对于必须为传递的参数初始化新对象的方法使用out。除此之外,ref和out的行为是一样的。