Home >Backend Development >C++ >How Can I Create Instances of Generic Types with Constructors in C#?

How Can I Create Instances of Generic Types with Constructors in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-22 13:42:111045browse

How Can I Create Instances of Generic Types with Constructors in C#?

Creating instances of generic types using constructors in C#

In C#, using constructors to create new objects of generic types can be a challenge. Consider the following scenario:

<code class="language-csharp">// 创建类型为T的对象列表
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>

When trying to compile this code, you may encounter a compiler error stating that an argument cannot be provided when creating an instance of variable T. This is because the new() constraint only allows the creation of objects without parameters.

Solution: Use function

To overcome this limitation, you can provide a parameter that allows the object to be created based on the parameter. A convenient solution is to use a function:

<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>

Call function

To use this function, you call it as follows:

<code class="language-csharp">GetAllItems<Foo>(..., l => new Foo(l));</code>

This approach allows you to create new objects of a generic type with a constructor, even within a generic function.

The above is the detailed content of How Can I Create Instances of Generic Types with Constructors 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