Home > Backend Development > C++ > Can C# Generic Methods Constrain Type Parameters to Specific Constructors?

Can C# Generic Methods Constrain Type Parameters to Specific Constructors?

Patricia Arquette
Release: 2025-01-14 16:01:44
Original
843 people have browsed it

Can C# Generic Methods Constrain Type Parameters to Specific Constructors?

Constructor constraints with parameter specification in C#

In C#, generic methods allow constraints to be imposed on type parameters. For example, the following code shows a constraint that requires parameter type T to have a parameterless constructor:

<code class="language-csharp">public class A {

    public static T Method<T>(T a) where T : new() {
        //...do something...
        return new T();
    }

}</code>
Copy after login

This begs the question: can we refine the constraints and specify that T should have a constructor that accepts a float[,] argument? Unfortunately, the following attempt fails to compile:

<code class="language-csharp">public class A {

    public static T Method<T>(T a) where T : new(float[,] u) {
        //...do something...
        return new T(new float[0,0]);
    }

}</code>
Copy after login

Solution

Since this constraint cannot be used, we can adopt a workaround and use a delegate to initialize an object of type T:

<code class="language-csharp">public class A {

    public static void Method<T>(T a, Func<float[,], T> creator) {
        //...do something...
    }

}</code>
Copy after login

The above is the detailed content of Can C# Generic Methods Constrain Type Parameters to Specific Constructors?. 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