【问题标题】:Passing a list parameter as ref [duplicate]将列表参数作为 ref 传递 [重复]
【发布时间】:2015-11-02 06:26:35
【问题描述】:

在 C# 中将列表作为参数作为 ref 传递有什么好处? List 不是值类型,因此对其所做的每次更改都会在返回函数后反映出来。

class Program
{
    static void Main(string[] args)
    {
        var myClass = new MyClass();
        var list = new List<string>();
        myClass.Foo(ref list);

        foreach (var item in list)
        {
            Console.WriteLine(item);
        }
    }
}

class MyClass
{
    public void Foo(ref List<string> myList)
    {
        myList.Add("a");
        myList.Add("b");
        myList.Add("c");
    }
}

我可以删除“ref”,它会正常工作。 所以我的问题是我们需要为列表、数组添加 ref 关键字的用途是什么... 谢谢

【问题讨论】:

标签: c# list ref


【解决方案1】:

ref 关键字导致参数通过引用而不是值传递。 List 是一种引用类型。在您的示例中,您尝试通过引用方法参数来传递对象,也使用 ref 关键字。

这意味着你正在做同样的事情。在这种情况下,您可以删除 ref 关键字。

ref 当你想通过引用传递一些值类型时需要。 例如:

class MyClass
{
    public void Foo(ref int a)
    {
        a += a;
    }
}

class Program
{
    static void Main(string[] args)
    {
        int intvalue = 3;
        var myClass = new MyClass();
        myClass.Foo(ref intvalue);
        Console.WriteLine(intvalue);    // Output: 6
    }
}

您可以在此处找到一些其他规格信息:ref (C# Reference)

【讨论】:

    【解决方案2】:

    这将创建新列表,并将替换外部的 list 变量:

    public void Foo(ref List<string> myList)
    {
        myList = new List<string>();
    }
    

    这不会从外部替换 list 变量:

    public void Foo(List<string> myList)
    {
        myList = new List<string>();
    }
    

    【讨论】:

    • 默认情况下集合作为引用传递,因此声明如果没有 ref 关键字就不会替换列表是错误的。
    猜你喜欢
    • 2012-08-26
    • 1970-01-01
    • 2021-12-14
    • 2019-07-23
    • 2018-01-20
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 2013-08-13
    相关资源
    最近更新 更多