Home >Backend Development >C++ >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>
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>
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>
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!