Home > Backend Development > C++ > How Can I Constrain a Generic Type to Have a Specific Constructor in C#?

How Can I Constrain a Generic Type to Have a Specific Constructor in C#?

Susan Sarandon
Release: 2025-01-14 16:07:44
Original
325 people have browsed it

How Can I Constrain a Generic Type to Have a Specific Constructor in C#?

C# Generic Types: Constructor Parameter Constraints

C# allows generic methods to be constrained to types possessing parameterless constructors (where T : new()). However, directly specifying a constructor with particular parameter types as a constraint isn't supported.

Example of a valid constraint:

<code class="language-csharp">public class A
{
    public static T Method<T>(T a) where T : new()
    {
        // ... some code ...
        return new T();
    }
}</code>
Copy after login

This correctly limits T to types with a default constructor. The following, however, will result in a compilation error:

<code class="language-csharp">public class A
{
    public static T Method<T>(T a) where T : new(float[,] u)
    {
        // ... some code ...
        return new T(new float[0, 0]);
    }
}</code>
Copy after login

Alternative Approach

To work around this limitation, utilize a delegate to provide a constructor accepting the required parameter type:

<code class="language-csharp">public class A
{
    public static void Method<T>(T a, Func<float[,], T> creator)
    {
        // ... some code ...
        T instance = creator(new float[0, 0]); // Create T using the supplied delegate
    }
}</code>
Copy after login

Here, the creator delegate receives a float[,] and returns a T instance. The Method function then employs this delegate for object creation. This offers flexibility in specifying constructor parameters without relying on direct constraint mechanisms.

The above is the detailed content of How Can I Constrain a Generic Type to Have a Specific Constructor in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template