【问题标题】:C# method out parameter list initialization doesn't works with Clear()C# 方法输出参数列表初始化不适用于 Clear()
【发布时间】:2023-04-10 22:53:01
【问题描述】:

我找到了,那个结构

Method(out List<T>list)
{
    list.Clear();      // doesn't allowed to initialyze List<T>list
    list = null;       // is accepted by VSTO, however, is not so good
}

有什么建议吗?

【问题讨论】:

  • out 参数通常用于在方法内创建的东西,而不是用于修改传递到方法中的东西。也许您应该使用ref。您需要显示将使用此代码的上下文。
  • 谢谢马特!实际上,我正在将类中的列表字段处理到方法中,例如 public Liststr = new List(); ...

标签: c# list initialization out


【解决方案1】:

您不能在此方法中使用未分配的参数。有一个简单的规则:如果参数未初始化,则使用out;如果将已初始化的参数传递给方法,则使用ref

此代码将正确运行:

void Method<T>(ref List<T> list)
{
    list.Clear();
    list = null;
}

阅读更多关于这个问题的不同之处:What's the difference between the 'ref' and 'out' keywords?

【讨论】:

    【解决方案2】:

    如果你想使用out 语义,而不是ref,你必须实例化你的列表:

    Method(out List<T>list)
    {
        list = new List<T>();
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-15
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 2018-06-24
      • 1970-01-01
      • 2020-03-29
      • 2015-03-26
      相关资源
      最近更新 更多