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

public void myFunction(ref MyClass someClass)

and

public void myFunction(out MyClass someClass)

我应该用哪个,为什么?


当前回答

ref和out就像c++中传递引用和传递指针一样。

对于ref,参数必须声明并初始化。

对于out,实参必须声明,但可以初始化,也可以不初始化

        double nbr = 6; // if not initialized we get error
        double dd = doit.square(ref nbr);

        double Half_nbr ; // fine as passed by out, but inside the calling  method you initialize it
        doit.math_routines(nbr, out Half_nbr);

其他回答

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

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,因为默认情况下只传递对实际对象的引用,因此您总是要更改引用后面的对象。

例子:

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

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

只要传入一个类,如果你想在方法中改变对象,就不必使用ref。

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

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

扩展狗和猫的例子。带有ref的第二个方法更改调用者引用的对象。所以叫“猫”!!

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

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

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