C#泛型约束:结构的数组 [英] C# generic constraint: Array of Structs

查看:230
本文介绍了C#泛型约束:结构的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建包含类型为值类型(结构),像数组的通用的限制:

 公共类X< T>其中T:结构[]

或者

 公共类X< T,U>
    其中U:结构
    其中T:U []

但是,这并不正常工作。看来的System.Array不能被用作类型约束。

所以 - 我该如何约束一个泛型参数是结构的数组?

第一个答案后更新:

 公共接口IDeepCopyable< T>
{
    ŧ正是deepcopy(T T);
}
公共类DeepCopyArrayOfValueTypes< T> :IDeepCopyable< T>
    其中,T:是值类型的数组
{
    ŧ复制(T(T)){...}
}


解决方案

您不需要。

只要将其约束到:结构,然后写 T [] 而不是 T使用类型参数时

 公共类DeepCopyArrayOfValueTypes< T> :IDeepCopyable< T []>
    其中T:结构
{
    大众T []正是deepcopy(T [] T){...}
}

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) {...}
}

解决方案

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) {...}
}

这篇关于C#泛型约束:结构的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆