C#數組
一維數組
using System;
namespace HelloWorld
{
class Program
{
static void Func(int[] param_ints)
{
for (int i = 0; i < param_ints.Length; i++)
{
param_ints[i] = 9;
}
}
static void Main(string[] args)
{
/**
* 1. 數組常見的初始化方式
*/
int[] ints1 = new int[10]; //new數組后元素會默認初始化為0
int[] ints2 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] ints3 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
/**
* 2. 遍歷元素
*/
for (int i = 0; i < ints1.Length; i++)
{
/**
* 輸出:
* 0 0 0 0 0 0 0 0 0 0 0
*/
Console.Write("{0} ", ints1[i]);
}
Console.WriteLine();
foreach (int i in ints2)
{
/*
* 輸出:
* 1 2 3 4 5 6 7 8 9 10
*/
Console.Write("{0} ", i);
}
Console.WriteLine();
/**
* 3. 數組賦值
*
* temp_ints是對ints的引用,因此ints1中元素被修改,
* temp_ints中元素也會被修改
*/
int[] temp_ints = ints1;
ints1[9] = 100;
/**
* 輸出:
* temp_ints[9]: 100, ints1[9]: 100
*/
Console.WriteLine("temp_ints[9]: {0}, ints1[9]: {1}", temp_ints[9], ints1[9]);
/**
* 4. 數組作為參數傳遞給函數
*
* 本質與"3.數組賦值"相同
*/
Func(ints3);
foreach (int i in ints3)
{
/**
* 輸出:
* 9 9 9 9 9 9 9 9 9 9
*/
Console.Write("{0} ", i);
}
Console.WriteLine();
}
}
}
?
多維數組
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
/*
* 1. 多維數組的形式
*/
/*二維數組*/
int[,] ints1 = new int[3, 4]
{
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
/*三維數組*/
int[,,] ints2 = new int[2,2,2]
{
{
{ 1, 2 },
{ 3, 4 }
},
{
{ 5, 6 },
{ 7, 8 }
}
};
/**
* 多維數組的初始化、賦值、遍歷等操作與一維數組類似,在此不多贅述
*/
}
}
}
?
交錯數組
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
/*1. 交錯數組形式*/
int[][] ints1 = new int[3][]
{
new int[] { 1, 2, 3},
new int[] { 4, 5, 6},
new int[] { 7, 8, 9}
};
/*2. 交錯數組的遍歷*/
for (int i = 0; i < ints1.Length; i++)
{
for (int j = 0; j < ints1[i].Length; j++)
{
/**
* 輸出:
* 1 2 3
* 4 5 6
* 7 8 9
*/
Console.Write(ints1[i][j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
for (int i = 0; i < ints1.Length; i++)
{
foreach (int item in ints1[i])
{
/**
* 輸出:
* 1 2 3
* 4 5 6
* 7 8 9
*/
Console.Write(item + " ");
}
Console.WriteLine();
}
/**
* 交錯數組的賦值與作為函數參數傳遞等相關操作與一維、多維數組一樣,在此不多贅述
*/
/**
* 3.交錯數組和多維數組的區別
*
* Ⅰ.交錯數組中的數組元素長度可以不一樣,而多維數組中每一維的長度必須一樣
* Ⅱ.交錯數組是數組的數組,而多維數組是一個整體
*/
int[,] ints2 = new int[,]
{
{ 1, 2, 3},
{ 4, 5}, //報錯,多維數組中每一維的長度必須一樣
{ 7, 8, 9}
};
int[][] ints3 = new int[3][]
{
new int[] { 1, 2, 3},
new int[] { 4, 5},
new int[] { 6, 7, 8, 9, 10}
};
}
}
}
?
參數數組
本文來自博客園,作者:Reimual,轉載請注明原文鏈接:http://www.rzrgm.cn/Reimual/p/19139857

浙公網安備 33010602011771號