Home >Backend Development >C++ >How Can I Pass Constructor Arguments to a Generic `new()` Constraint in C#?
new()
constructor parametersQuestion:
A compilation error occurs when trying to create a new object of type T with a constructor argument in a generic method using the new()
constraint. The error message states that the parameter cannot be supplied during object initialization.
<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>
Solution:
To create an object of a generic type using constructor arguments, it is not enough to just use the new
constraint. A custom function must be introduced to handle initialization with necessary parameters. Here’s how:
<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>
By using a custom function, you can call a generic method, specify the type and provide an initialization function as follows:
<code class="language-csharp">GetAllItems<Foo>(..., l => new Foo(l));</code>
The above is the detailed content of How Can I Pass Constructor Arguments to a Generic `new()` Constraint in C#?. For more information, please follow other related articles on the PHP Chinese website!