Domanda

I would like to create a generic constraint that contains the type to be an array of value types (structs), something like:

public class X<T> where T : struct[]

or maybe

public class X<T, U>
    where U : struct
    where T : U[]

but this doesn't work. It seems System.Array cannot be used as type constraint.

So - how do I constrain a generic parameter to be an array of structs?

Updated after first answer:

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) {...}
}
È stato utile?

Soluzione

You don't need to.

Just constrain it to : struct, then write T[] instead of T when using the type parameter.

public class DeepCopyArrayOfValueTypes<T> : IDeepCopyable<T[]>
    where T : struct
{
    public T[] DeepCopy(T[] t) {...}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top