Home >Backend Development >C++ >How Can I Pass Constructor Arguments to a Generic `new()` Constraint in C#?

How Can I Pass Constructor Arguments to a Generic `new()` Constraint in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-22 13:36:14283browse

How Can I Pass Constructor Arguments to a Generic `new()` Constraint in C#?

Passing generics for template types in C# new() constructor parameters

Question:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn