编译器错误 CS1954

更新:2007 年 11 月

错误消息

无法使用集合初始值设定项元素的最佳重载方法匹配项“method”。集合初始值设定项“Add”方法不能具有 ref 或 out 参数。

为了使用集合初始值设定项初始化集合类,此类必须具有 publicAdd 方法,且该方法不是 ref 或 out 参数。

更正此错误

  • 如果可以修改该集合类的源代码,则提供一个不采用 ref 或 out 参数的 Add 方法。

  • 如果无法修改该集合类,则使用它所提供的构造函数对其进行初始化。集合初始值设定项无法与集合类一起使用。

示例

下面的示例将生成 CS1954,因为 MyList 中的 Add 列表的唯一可用重载具有 ref 参数。

// cs1954.cs
using System.Collections.Generic;
class MyList<T> : IEnumerable<T>
{
    List<T> _list;
    public void Add(ref T item)
    {
        _list.Add(item);
    }

    public System.Collections.Generic.IEnumerator<T> GetEnumerator()
    {
        int index = 0;
        T current = _list[index];
        while (current != null)
        {
            yield return _list[index++];
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

public class MyClass
{
    public string tree { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        MyList<MyClass> myList = new MyList<MyClass> { new MyClass { tree = "maple" } }; // CS1954
    }
}

请参见

参考

对象和集合初始值设定项(C# 编程指南)