編譯器錯誤 CS1954
更新:2007 年 11 月
錯誤訊息
無法使用集合初始設定式項目之最符合的多載方法 'method'。集合初始設定式 'Add' 方法不能具有 ref 或 out 參數。
若是要使用集合初始設定式來初始化的集合類別 (Collection Class),該類別必須具有不採用 ref 或 out 參數的 publicAdd 方法。
若要修正這個錯誤
如果您可以修改集合類別的原始程式碼,請提供不採用 ref 或 out 參數的 Add 方法。
如果您無法修改集合類別,則請用該集合類別所提供的建構函式 (Constructor) 來初始化該類別。您不能對它使用集合初始設定式。
範例
因為 MyList 中 Add 清單的唯一可用多載具有 ref 參數,所以下列範例會產生 CS1954。
// 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
}
}