search
HomeBackend DevelopmentC#.Net TutorialC# basic knowledge compilation: basic knowledge (14) array

No matter which language, there will definitely be the concept of collection. The simplest and most intuitive collection should be an array. An array is a continuous space in memory. Take a look at the definition of array

in C#.
1. int[] intArry;
intArry= new int[6];
Here declares an int array type variable intArry and saves an int array object with 6 units;
int [,] intArry2 = new int[3, 4];
Declare an int two-dimensional array type variable and initialize an array object with 3 rows and 4 columns;
int[][] intArry3 = new int[9 ][];
Declare an array unit as an array variable of int array type. Each array element is an object reference of int array type.
Because it is an object-oriented language, references and objects are mentioned above. In fact:
1. The .net Frameword array is not a simple data structure, but a type, called an array type;
2. The array variable in the .net Framework stores references to array type objects. That is to say, the array is an object.
All .net Framework arrays (int[], string[], object[]) are subclasses inherited from Array. Generally, the Array class is not used directly, because various languages ​​under the .net Framework, including C# of course, map array objects to their own special syntax, such as int[], string[].

The array mainly has two attributes: index and length, that is, index and length. The index is used to access the elements in the array object, and the length is the length of the array.

Look at a piece of contact code:

public class MyArray
    {
        /// <summary>
        /// 定义数组测试
        /// </summary>
        public void TestInt()
        {
            int[] intArry1 = null;

            intArry1 = new int[6];

            int[,] intArry2 = new int[3, 4];

            int[][] intArry3 = new int[9][];
        }
        
        /// <summary>
        /// 值类型数组转引用类型数组测试
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        public static object[] Int32ToArrayOfObject(int[] array)
        {
            object[] objArray = new object[array.Length];

            for (int i = 0; i < array.Length; i++)
            {
                objArray[i] = array[i];
            }

            return objArray;
        }
        /// <summary>
        /// 数组的主要特性测试
        /// </summary>
        public static void MainTest()
        {
            //声明一个包含是个元素的字符串型数组
            string[] sArray = new string[10];
            //访问数组
            //赋值
            for (int i = 0; i < sArray.Length; i++)
            {
                sArray[i] = @"string" + i;
            }

            ConsoleToClientString(sArray);

            //另一种方式声明数组,所谓的枚举法
            sArray = new string[] { "TestString0", "TestString1", "TestString2" };

            ConsoleToClientString(sArray);

            //数组复制
            string[] newSArray = sArray.Clone() as string[];

            ConsoleToClientString(newSArray);

            //使用Array的CreateInstance方法声明10元素的整形数组
            int[] intArray = Array.CreateInstance(typeof(int), 10) as int[];

            for (int i = 0; i < intArray.Length; i++)
            {
                intArray[i] = i;
            }

            ConsoleToClientInt(intArray);

            //数组之间的复制,指定位置,指定长度
            int[] newIntArray = new int[20];

            Array.Copy(intArray, 3, newIntArray, 4, intArray.Length - 3);

            ConsoleToClientInt(newIntArray);

            object[] objArray = sArray;

            ConsoleToClientObject(objArray);

            objArray = Int32ToArrayOfObject(intArray);

            ConsoleToClientObject(objArray);

            //数组的数组
            int[][] intArrayArray = new int[9][];

            Console.WriteLine("数组长度:" + intArrayArray.Length);

            //赋值
            for (int i = 1; i < 10; i++)
            {
                intArrayArray[i - 1] = new int[i];

                for (int j = 1; j <= i; j++)
                {
                    intArrayArray[i - 1][j - 1] = i * j;
                }
            }

            ConsoleToClientArrayArrayInt(intArrayArray);
            
            //二维数组
            int[,] intArray2D = new int[9, 9];

            Console.WriteLine(string.Format("二维数组 长度:{0},维数:{1}*{2}", intArray2D.Length, 

intArray2D.GetLength(0), intArray2D.GetLength(1)));

            for (int i = 1; i < 10; i++)
            {
                for (int j = 1; j <= i; j++)
                {
                    intArray2D[i - 1, j - 1] = i * j;
                }
            }

            int count = 0;

            foreach (int item in intArray2D)
            {
                if (item > 0)
                {
                    Console.Write("{0,2}", item);
                }

                if (++count >= 9)
                {
                    Console.WriteLine();

                    count = 0;
                }
            }
        }

        static void ConsoleToClientArrayArrayInt(int[][] intArrayArray)
        {
            foreach (int[] item1 in intArrayArray)
            {
                foreach (int item2 in item1)
                {
                    Console.Write("{0,2}", item2);
                }

                Console.WriteLine();
            }

            Console.WriteLine();
        }

        static void ConsoleToClientString(string[] sArray)
        {
            foreach (string item in sArray)
            {
                Console.Write(item + @",");
            }

            Console.WriteLine();
        }

        static void ConsoleToClientInt(int[] intArray)
        {
            foreach (int item in intArray)
            {
                Console.Write(item + @",");
            }

            Console.WriteLine();
        }

        static void ConsoleToClientObject(object[] objArray)
        {
            foreach (object item in objArray)
            {
                Console.Write(item.ToString() + @",");
            }

            Console.WriteLine();
        }

    }

Call

    class Program
    {
        static void Main(string[] args)
        {
            MyArray.MainTest();

            Console.ReadLine();
        }
    }

Result


You can know from the above: The array has a reference Type array and value type array. For reference type array, the element is used to save the reference of the object, and the initialization value is null; for value type array, the element saves the value of the

object, and for the numeric type, the initialization value is 0.

Arrays have dimensions, but multidimensional arrays and arrays of arrays are different concepts. intArrayArray and intArray2D are different. The array of array represents an m*n determinant


, and the multidimensional array is an array in which each element is an array object.

Arrays, like other collection classes, implement the ICollection interface and have enumeration and iteration functions.


The above is the compilation of C# basic knowledge: Basic knowledge (14) Array content. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment