为什么不能System.Array的是一个类型的约束? [英] Why can't System.Array be a type constraint?
问题描述
我工作的一个小项目,有一些不同类型的数组(如双[]
,浮法[]
, INT []
。为了验证/测试/神智的目的,我打印出一些阵列的控制台,因为我走。所以我有多个看起来像下面的这些功能(简化这个例子 - 假设我只用一维数组处理):
I'm working on a small project with a few different types of arrays (e.g. double[]
, float[]
, int[]
. For verification / testing / sanity purposes, I'm printing out some of these arrays to the console as I go along. So I have multiple functions that look like these below (simplified for this example - assume I'm only dealing with single-dimension arrays):
void Print(float[] a) // prints an array of floats
{
for (int i = 0; i < a.Length; i++)
{
Console.Write(a[i]);
}
}
void Print(double[] a) // prints an array of doubles
{
for (int i = 0; i < a.Length; i++)
{
Console.Write(a[i]);
}
}
我,在我无穷的智慧,以为我可以简单地创建这些功能的通用版本减少一些code重复。所以,我想这样的:
I, in my infinite wisdom, thought I could reduce some of the code duplication by simply creating a generic version of these functions. So I tried this:
void Print<T>(T t) where T : Array
{
for (int i = 0; i < t.Length; i++)
{
Console.Write(t.GetValue(i));
}
}
智能感知是没有抱怨,但是编译器失败,一个很有趣的错误:
Intellisense isn't complaining, but the compiler fails with a very interesting error:
约束不能成为特殊阶层的System.Array
我看了一个解释(类似于对象
或密封类,但没有发现太多,除了一提的on MSDN 。任何人都可以向我解释的为什么的是这种情况?为什么我不能指定类型的System.Array
?
I've looked for an explanation (similar to Object
or sealed classes, but haven't found much, besides a mention on msdn. Can anyone explain to me why this is the case? Why can't I specify a type constraint of System.Array
?
PS:虽然打字了这一点,我意识到,我可以完成我本来想更轻松,像这样一个简单的功能:
p.s.: While typing this out, I realized that I can accomplish what I originally wanted more easily, with a simple function like this:
void Print(System.Array a)
{
for (int i = 0; i < a.Length; i++)
{
Console.Write(a.GetValue(i));
}
}
这是为什么有在编译器?
Is this why there's a special rule for arrays in the compiler?
推荐答案
适当的语法,做你想做的是这样的:
The appropriate syntax to do what you want is this:
void Print<T>(T[] array)
{
for (int i = 0; i < array.Length; i++)
{
Console.Write(array[i]);
}
}
这篇关于为什么不能System.Array的是一个类型的约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!