简体   繁体   English

这两种方法有什么区别——通过ref

[英]What is the difference between these two methods - pass by ref

What is the difference between the code below?下面的代码有什么区别? Both methods achieve the same output of removing 4 from the list.两种方法都实现了从列表中删除 4 的相同输出。

static void Main(string[] args)
{
    var list = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9};
    ModifyList(ref list);
    Console.WriteLine(string.Join(", ", list));

    list.Add(4);
    ModifyList(list);
    Console.WriteLine(string.Join(", ", list));

    Console.ReadLine();
}

public static void ModifyList(ref List<int> list)
{
     list.Remove(4);
}

public static void ModifyList(List<int> list)
{
     list.Remove(4);
}

In this case, both do exactly the same thing.在这种情况下,两者都做完全相同的事情。 The difference between passing the argument in by ref is that if you assign to the variable itself (eg. list = new List<int>(); , it will update the reference of the caller to point to the new list as well.通过 ref 传入参数的区别在于,如果您分配给变量本身(例如list = new List<int>(); ,它将更新调用者的引用以指向新列表。

See Passing Reference-Type Parameters (C# Programming Guide) for more info.有关详细信息,请参阅传递引用类型参数(C# 编程指南)

In this case the only difference is under the hood and not easily noticeable, the difference is that in the ModifyList(ref List<int> list) the list object is passed by reference and so the original reference (managed pointer) is the same as the original object passed, while in the second case the reference is copied to another reference so the list argument is basically a reference to another reference that point to the real object .在这种情况下,唯一的区别是在幕后并且不容易注意到,区别在于ModifyList(ref List<int> list)的列表对象是通过引用传递的,因此原始引用(托管指针)与传递的原始对象,而在第二种情况下,引用被复制到另一个引用,因此列表参数基本上是对指向真实对象的另一个引用的引用。

The result you get is the same, because in C# with safe reference is totally transparent to you but if you would have used C or C++ with raw pointers you would have noticed that in the second case you would had to dereference the pointer two times to access the object ...你得到的结果是一样的,因为在 C# 中,安全引用对你来说是完全透明的,但是如果你将 C 或 C++ 与原始指针一起使用,你会注意到在第二种情况下你必须两次取消引用指针访问对象...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM