为什么 System.Array 不能是类型约束? [英] Why can't System.Array be a type constraint?

查看:29
本文介绍了为什么 System.Array 不能是类型约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个包含几种不同类型数组的小项目(例如 double[]float[]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]);
    }
}

以我无限的智慧,我认为我可以通过简单地创建这些函数的通用版本来减少一些代码重复.所以我尝试了这个:

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 没有抱怨,但编译器失败并出现一个非常有趣的错误:

Intellisense isn't complaining, but the compiler fails with a very interesting error:

约束不能是特殊类'System.Array'

我已经寻找了一个解释(类似于 Object 或密封类,但没有找到太多,除了提到 在 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屋!

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