Pass parameters to new()
of C# generic template type
When trying to create a new object of generic type T using its constructor during list expansion, you may encounter a compilation error claiming "T: cannot supply arguments when creating variable instance".
This error occurs because you are trying to call a constructor with parameters for a generic type that is constrained using the "new" flag, which only allows instantiation of objects without constructor parameters.
Solution:
To create an object of a generic type with constructor parameters, you need to remove the "new" constraint and instead provide a delegate that creates the object based on the specified parameters. Here's an example:
<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>
This function accepts a delegate del
which takes a ListItem as parameter and returns an object of type T. You can then call this function and pass the lambda expression as a delegate to create an object of the required type with the necessary parameters:
<code class="language-csharp">GetAllItems<Foo>(..., l => new Foo(l));</code>
By using delegates, you can provide custom initialization logic for the objects you want to create while still maintaining the flexibility of generic programming.
The above is the detailed content of How to Pass Arguments to a C# Generic `new()` Constraint When Creating Objects?. For more information, please follow other related articles on the PHP Chinese website!