我正在创建一个函数,我需要传递一个对象,以便它可以被函数修改。有什么区别:

public void myFunction(ref MyClass someClass)

and

public void myFunction(out MyClass someClass)

我应该用哪个,为什么?


当前回答

迟了回答,但想到了发帖。可能比其他答案更清楚一点。

ref的关键字:

ref is a keyword which is used to pass any value by reference(refer to call by value and call by reference in programming for further knowledge). In short, you declare and initialize a value for example let us say int age = 5; so this age is saved in the memory by holding a place of 4 bytes. Now if you are passing this age variable to another method with ref (which means passing them by reference and not by value) then the compiler will just pass the reference of that variable or in clear terms, the memory address of the place where the variable is stored and the called method receives this address and directly accesses the data in that address. So obviously any change to that data will happen also to the variable present in the calling method.

示例:我提供了我的stackoverflow帐户的密码并告诉他 他可以做任何他想做的事,他可以提问或回答。的 问题是,他做的任何改变都会直接影响到我的账户。

关键字:

Out和in类似于它们都传递变量的引用。现在我们知道,两者都需要传递变量的引用,很明显,内存中必须有一个地方保存变量的字节。但在out的情况下没有初始化。因为要求是,被调用的方法必须初始化值并返回它。

示例:我将stackoverflow站点地址发送给我的朋友并询问 让他帮我开个账户,把证件还给我。

关键字:

现在,in关键字的工作原理与ref关键字完全相同,只有一个条件,即作为引用传递的值不能被修改。

示例:我提供了我的stackoverflow帐户的密码,但告诉了他 不做任何事情,除了阅读或浏览网站。不要问 问题,没有答案,没有投票,什么都没有。

MSDN引用:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/in-parameter-modifier

希望以上说明清楚了。

其他回答

我要试着解释一下:

我想我们理解了值类型是如何工作的,对吧?值类型是(int, long, struct等)。当你将它们发送到一个没有ref命令的函数时,它会复制数据。在函数中对该数据所做的任何操作都只会影响副本,而不会影响原始数据。ref命令发送的是实际数据,任何变化都会影响函数外部的数据。

好了,让人困惑的部分,引用类型:

让我们创建一个引用类型:

List<string> someobject = new List<string>()

当你新建someobject时,会创建两部分:

存储某对象数据的内存块。 指向该块的引用(指针) 的数据。

现在,当你发送someobject到一个没有引用的方法时,它复制的是引用指针,而不是数据。现在你得到了这个:

(outside method) reference1 => someobject
(inside method)  reference2 => someobject

两个引用指向同一个对象。如果你使用reference2修改某个对象的属性,它将影响由reference1指向的相同数据。

 (inside method)  reference2.Add("SomeString");
 (outside method) reference1[0] == "SomeString"   //this is true

如果你清空了reference2或将其指向新的数据,它不会影响reference1和reference1所指向的数据。

(inside method) reference2 = new List<string>();
(outside method) reference1 != null; reference1[0] == "SomeString" //this is true

The references are now pointing like this:
reference2 => new List<string>()
reference1 => someobject

当你将someobject by ref发送给方法时会发生什么? 对某个对象的实际引用被发送给方法。所以你现在只有一个数据引用:

(outside method) reference1 => someobject;
(inside method)  reference1 => someobject;

但这意味着什么呢?它的作用与不通过ref发送someobject完全相同,除了两件主要的事情:

1)当你清空方法内部的引用时,它也会清空方法外部的引用。

 (inside method)  reference1 = null;
 (outside method) reference1 == null;  //true

2)你现在可以将引用指向一个完全不同的数据位置,函数外部的引用现在将指向新的数据位置。

 (inside method)  reference1 = new List<string>();
 (outside method) reference1.Count == 0; //this is true

注意,在函数内部传递的引用参数是直接处理的。

例如,

    public class MyClass
    {
        public string Name { get; set; }
    }

    public void Foo()
    {
        MyClass myObject = new MyClass();
        myObject.Name = "Dog";
        Bar(myObject);
        Console.WriteLine(myObject.Name); // Writes "Dog".
    }

    public void Bar(MyClass someObject)
    {
        MyClass myTempObject = new MyClass();
        myTempObject.Name = "Cat";
        someObject = myTempObject;
    }

这会写狗,而不是猫。因此,您应该直接在someObject上工作。

裁判上场又出局。

您应该优先使用out,只要它能满足您的需求。

裁判: ref关键字用于将参数作为引用传递。这意味着当该参数的值在方法中被更改时,它会反映在调用方法中。使用ref关键字传递的参数在传递给被调用方法之前必须在调用方法中初始化。

: out关键字也用于传递一个参数,如ref关键字,但参数可以在不给它赋值的情况下传递。使用out关键字传递的参数在返回调用方法之前必须在被调用方法中初始化。

public class Example
{
 public static void Main() 
 {
 int val1 = 0; //must be initialized 
 int val2; //optional

 Example1(ref val1);
 Console.WriteLine(val1); 

 Example2(out val2);
 Console.WriteLine(val2); 
 }

 static void Example1(ref int value) 
 {
 value = 1;
 }
 static void Example2(out int value) 
 {
 value = 2; 
 }
}

/* Output     1     2     

在方法重载中引用和out

ref和out不能同时用于方法重载。然而,ref和out在运行时的处理方式不同,但在编译时的处理方式相同(CLR在为ref和out创建IL时不区分两者)。

为了说明这些优秀的解释,我开发了以下控制台应用程序:

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的行为是一样的。