Code Bye

为什么不能用数组做函数的参数

    class Program
    {
        static void f(System.Int32[])//为什么是编译错误?
        {
        }
        static void Main(string[] args)
        {
            var s = new[] { 1, 2, 3 };
            Console.WriteLine(s.ToString());//打印System.Int32[]
            f(s);
        }
    }

上面的小程序会有便衣错误,f的参数不能是这种形式。
问题,既然s就是System.Int32[],那么为它的类型还”不能”作为参数传递的类型呢,必须要转成其他的类型才可以? 这个是.net的运行时限制还是C#语言本身的某种限制?
谢谢。

解决方案

10

static void f(System.Int32[])
->
static void f(int[] arr)
var s = new[] { 1, 2, 3 };
->
var s = new int[] { 1, 2, 3 };

10

static void f(System.Int32[] s)

10

传参的基本概念是 :先声明类型,然后接着是该类型名字。
static void f(int[] arr)

10

你只传了类型,未定义类型名称

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明为什么不能用数组做函数的参数