我正在创建一个函数,我需要传递一个对象,以便它可以被函数修改。有什么区别:
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)
我应该用哪个,为什么?
当前回答
除了允许你将别人的变量重新分配给类的不同实例,返回多个值等,使用ref或out可以让别人知道你需要从他们那里得到什么,以及你打算用他们提供的变量做什么
You don't need ref or out if all you're going to do is modify things inside the MyClass instance that is passed in the argument someClass. The calling method will see changes like someClass.Message = "Hello World" whether you use ref, out or nothing Writing someClass = new MyClass() inside myFunction(someClass) swaps out the object seen by the someClass in the scope of the myFunction method only. The calling method still knows about the original MyClass instance it created and passed to your method You need ref or out if you plan on swapping the someClass out for a whole new object and want the calling method to see your change Writing someClass = new MyClass() inside myFunction(out someClass) changes the object seen by the method that called myFunction
还有其他程序员
他们想知道你将如何处理他们的数据。假设您正在编写一个将被数百万开发人员使用的库。你想让他们知道当他们调用你的方法时你要对他们的变量做什么
Using ref makes a statement of "Pass a variable assigned to some value when you call my method. Be aware that I might change it out for something else entirely during the course of my method. Do not expect your variable to be pointing to the old object when I'm done" Using out makes a statement of "Pass a placeholder variable to my method. It doesn't matter whether it has a value or not; the compiler will force me to assign it to a new value. I absolutely guarantee that the object pointed to by your variable before you called my method, will be different by the time I'm done
顺便说一下,在c# 7.2中也有一个in修饰符
And that prevents the method from swapping out the passed in instance for a different instance. Think of it like saying to those millions of developers "pass me your original variable reference, and I promise not to swap your carefully crafted data out for something else". in has some peculiarities, and in some cases such as where an implicit conversion might be required to make your short compatible with an in int the compiler will temporarily make an int, widen your short to it, pass it by reference and finish up. It can do this because you've declared you're not going to mess with it.
微软对数值类型的.TryParse方法做到了这一点:
int i = 98234957;
bool success = int.TryParse("123", out i);
通过将参数标记为out他们在这里积极地声明"我们肯定会将你苦心制作的98234957值更改为其他值"
当然,对于像解析值类型这样的事情,它们有点不得不这样做,因为如果parse方法不允许将值类型替换为其他类型,那么它就不能很好地工作。但是想象一下在你创建的库中有一些虚构的方法:
public void PoorlyNamedMethod(out SomeClass x)
你可以看到它是一个out,因此你可以知道,如果你花了几个小时处理数字,创建一个完美的SomeClass:
SomeClass x = SpendHoursMakingMeAPerfectSomeClass();
//now give it to the library
PoorlyNamedMethod(out x);
那真是浪费时间,花那么多时间来做一节完美的课。它肯定会被丢弃,并被PoorlyNamedMethod取代
其他回答
假设多姆因为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的行为是一样的。
Ref和out的行为类似,只是有一些不同。
引用变量必须在使用前初始化。Out变量无需赋值即可使用 Out形参必须被使用它的函数视为未赋值。因此,我们可以在调用代码中使用初始化的out形参,但该值将在函数执行时丢失。
有两个主要的区别,我想举例说明:
Ref和out通过reference传递,hense;
class Program
{
public static void Main(string[] args)
{
var original = new ObjectWithMememberList(3);
Console.WriteLine(original.MyList.Capacity); // 3
ChangeList(original.MyList);
Console.WriteLine(original.MyList.Capacity); // 3
}
static void ChangeList(List<int> vr)
{
vr = new List<int>(2);
}
}
but:
class Program
{
public static void Main(string[] args)
{
var original = new ObjectWithMememberList(3);
Console.WriteLine(original.MyList.Capacity); // 3
ChangeList(ref original.MyList);
Console.WriteLine(original.MyList.Capacity); // 2
}
static void ChangeList(ref List<int> vr)
{
vr = new List<int>(2);
}
}
out也是一样。 2. Ref参数必须是一个可赋值变量。 hense:
ChangeList(ref new List<int>()); // Compile Error [might not be initialized before accessing]
but:
List<int> xs;
ChangeList(out xs); // Compiles
Ref表示Ref参数中的值已经设置,方法可以读取和修改它。 使用ref关键字等同于说调用方负责初始化形参的值。
Out告诉编译器,对象的初始化是由 函数需要赋值给out形参。 没有分配是不允许的。
https://www.codemaggot.com/ref-and-out-keywords/