我想通過一個通用列表到一個函數,將添加一個新項目的列表。我有以下的剝離下來的例子:通用方法添加新T到列表T
private void SetBayNumb<T>(ObservedList<T> bayList) where T : IBaySpec, new()
{
var bay = new T();
bayList.Add(bay);
}
的方法調用它有這個錯誤:
The type
T' must have a public parameterless constructor in order to use it as parameter
T' in the generic type or method
正是我試圖做可能嗎?我覺得它一定是因爲編譯器不應該關心它是什麼樣的列表 - 它只需要調用公共的無參數構造函數並將新實例添加到已傳入的現有列表中。
我猜對了問題是,接口不出示擔保其實施者將有一個公共的構造,但即使我給它一個具體的類我得到這個錯誤:
The type
T' must be convertible to
BayClass' in order to use it as parameter `T' in the generic type or method
將是任何指針非常感謝。
您正在收到錯誤,因爲您指定的類型不符合通用約束條件。 – 2015-02-05 22:02:27
顯示調用它的方法 - 顯然它使用的是一個沒有公共無參數構造函數的類型(記住構造函數沒有被繼承) – 2015-02-05 22:02:40
閱讀錯誤信息它告訴你到底發生了什麼錯誤。 – MethodMan 2015-02-05 22:03:17