new()
建構子參數問題:
在使用 new()
限制的泛型方法中嘗試建立具有建構函式參數的型別 T 的新物件時,會出現編譯錯誤。錯誤訊息指出在物件初始化期間無法提供參數。
<code class="language-csharp">public static string GetAllItems<T>(...) where T : new() { List<T> tabListItems = new List<T>(); foreach (ListItem listItem in listCollection) { tabListItems.Add(new T(listItem)); // 此处出错。 } ... }</code>
解:
要使用建構子參數建立泛型類型的對象,僅使用 new
限制是不夠的。必須引入一個自訂函數來處理具有必要參數的初始化。方法如下:
<code class="language-csharp">public static string GetAllItems<T>(..., Func<ListItem, T> del) { ... List<T> tabListItems = new List<T>(); foreach (ListItem listItem in listCollection) { tabListItems.Add(del(listItem)); // 使用函数创建对象。 } ... }</code>
透過使用自訂函數,可以如下呼叫泛型方法,指定類型並提供初始化函數:
<code class="language-csharp">GetAllItems<Foo>(..., l => new Foo(l));</code>
以上是如何在 C# 中將建構函數參數傳遞給通用 `new()` 約束?的詳細內容。更多資訊請關注PHP中文網其他相關文章!