C#generic constraint:Structs数组

Wil*_*ert 2 c# arrays generics value-type generic-constraints

我想创建一个通用约束,其中包含类型为值类型(结构)的数组,类似于:

public class X<T> where T : struct[]
Run Code Online (Sandbox Code Playgroud)

或者可能

public class X<T, U>
    where U : struct
    where T : U[]
Run Code Online (Sandbox Code Playgroud)

但这不起作用.似乎System.Array不能用作类型约束.

那么 - 如何将泛型参数约束为结构数组?

第一个回答后更新:

public interface IDeepCopyable<T>
{
    T DeepCopy(T t);
}


public class DeepCopyArrayOfValueTypes<T> : IDeepCopyable<T>
    where T : is an array of value types
{
    T Copy(T t) {...}
}
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 12

你不需要.

只需将其约束 : struct,然后写入T[]而不是T使用type参数.

public class DeepCopyArrayOfValueTypes<T> : IDeepCopyable<T[]>
    where T : struct
{
    public T[] DeepCopy(T[] t) {...}
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这会将您约束为*不可为空*结构的数组. (3认同)