我工作的一个小项目,有一些不同类型的数组(如双[]
,浮法[]
, 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
我看了一个解释(类似于对象
或密封类,但没有发现太多,除了一提的
相关推荐
最新文章