• C# 数组


    二维数组由若干个一维数组组成。

    在C++中,组成二维数组的一维数组长度必须相等。在C#中却可以不相等。

    C#二维数组有两种:

    1,普通二维数组:

    int [,] arr2d = new int[3,2];
    int[,] scroes2d2 = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };

    2,数组的数组:又称锯齿数组,交错数组

    int[][] varr = new int[3][] //不能写成int[][] varr = new int[3][2]
    int[][] varr2 = new int[3][] { new int[1] { 1 }, new int[3] { 1, 2, 3 }, new int[2] { 1, 2 } };

    测试代码:

    class Program
        {
            static void Main(string[] args)
            {
                int[] scroes = new int[5];
                int[,] scroes2d = new int[3,2];
                Console.WriteLine("scroes2d.length:{0}", scroes2d.Length); //6
                for(int i=0; i<3; ++i)
                {
                    for(int j=0; j<2; ++j)
                    {
                        scroes2d[i, j] = i * 2 + j;
                    }
                }
    
                int[][] varr = new int[3][];
                Console.WriteLine("varr.length:{0}", varr.Length); //3
                for(int i=0; i<varr.Length; ++i)
                {
                    varr[i] = new int[i + 1];
                    for(int j=0; j<varr[i].Length; ++j)
                    {
                        varr[i][j] = j;
                    }
                }
                foreach(var arr in varr)
                {
                    foreach(var n in arr)
                    Console.Write(n);
                    Console.WriteLine();
                }
                Console.ReadKey();
            }
    
        }
    • 附:参数数组

    有时,当声明一个方法时,您不能确定要传递给函数作为参数的参数数目。C# 参数数组解决了这个问题,参数数组通常用于传递未知数量的参数给函数。

    在使用数组作为形参时,C# 提供了 params 关键字,使调用数组为形参的方法时,既可以传递数组实参,也可以只传递一组数组。params 的使用格式为:

    public 返回类型 方法名称( params 类型名称[] 数组名称 )

        class CTest
        {
            public void func(params int[] arr)
            {
                foreach(var n in arr)
                {
                    Console.Write(n + ",");
                }
            }
        }
        class Program
        {
            static void Main(string[] args)
            {

                  CTest ot = new CTest();
                  ot.func(1,2,3,4,5,6,7,8,9,0);
                  ot.func(new int[] { 1, 2, 3, 4 });

         }
            }

  • 相关阅读:
    结构型模式代理&适配器
    创建型模式单例&工厂&建造者&原型
    结构型模式装饰者&桥接&门面
    python中列表(list)的使用
    Win2003 域控制器设置和客户端安装
    Python下冒泡排序的实现
    乔布斯在斯坦福大学毕业典礼上的演讲
    字符串替换
    统计文件中某一字符串出现的次数
    [用户 'sa' 登录失败。原因: 该帐户被禁用]的解决方案
  • 原文地址:https://www.cnblogs.com/timeObjserver/p/5926084.html
Copyright © 2020-2023  润新知