[英]Generics to constrain an N-dimensional array
Is there a way to constrain a generic type to be an n-dimensional array? 有没有办法将泛型类型约束为n维数组?
So, T[]
, T[,]
, T[,,]
, ... etc. 所以,
T[]
, T[,]
, T[,,]
......等
I'm basically trying to add an extension method to any type of arrays of that type I have. 我基本上试图将扩展方法添加到我所拥有的任何类型的数组中。 So I'm looking to get a combination of these methods using generics so I don't need to repeat the code inside
所以我希望使用泛型来获得这些方法的组合,所以我不需要在里面重复代码
public static bool IsFull(this MyType[] self) { ... }
public static bool IsFull(this MyType[,] self) { ... }
public static bool IsFull(this MyType[,,] self) { ... }
One method looks like this, but should have the exact same logic for [,]
, [,,]
etc: 一种方法看起来像这样,但应该具有
[,]
, [,,]
等完全相同的逻辑:
public static bool IsFull(this MyType[] self)
for (int i=0; i < self.Length; i++) {
MyType t = self.GetValue(i);
if (t == null || !t.IsFull()) {
return false;
}
}
return true;
I believe you'll eventually have to check if your array element is an instance of MyType
or another array - if that's acceptable then perhaps you can add an extension on System.Array
- something like this: 我相信你最终必须检查你的数组元素是否是
MyType
或另一个数组的实例 - 如果这是可以接受的,那么也许你可以在System.Array
上添加一个扩展 - 如下所示:
public static class Extension
{
public static bool IsFull(this Array self)
{
for (int i = 0; i < self.Length; i++)
{
var t = self.GetValue(i);
var arrT = t as Array;
var tt = t as MyType;
if (t == null || (arrT != null && !arrT.IsFull()) || (tt != null && !tt.IsFull()))
{
return false;
}
}
return true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.