C#方法输出参数列表初始化不适用于Clear()

时间:2016-11-17 13:11:55

标签: c# list initialization out

我找到了那个建筑

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
}

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

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

此代码将正确运行:

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

在此问题中详细了解差异:What's the difference between the 'ref' and 'out' keywords?

答案 1 :(得分:2)

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

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