C#基本笔记(1)—— C# 基础语法
一、C#变量的概念和数据类型
1. 变量的概念
概念:变量是存储内容的别名,通过变量可以访问到内容。
为什么要使用变量?
变量的赋值格式:
<data type><variable_name>=value;
例: int a = 10;
2. 数据类型取值范围
3. 常用的数据类型
char和string:
char表示一个字符,string是一个char类型的数组。
// 匈牙利命名法(驼峰式)
int hpValue = 1000;
int iHpValue = 2000;// i表示int
// 可单行赋值多个相同数据类型的变量
int c = 30, d = 40;
// string str
string strMonster = "树人";
// char ch
char chUnicode = 'a';
// short sh
short shID = 100;
// long l
long lMpValue = 1000;
// bool true : false b/is
bool bOpen = true;
// 输出格式化,范例如下
Debug.LogFormat("名字{0},血量{1},等级{2},经验值{3}", strName, iHpValue, iLevel, IExp);
二、C#数组
1. 数组概念
数组,是有序的相同数据类型元素组成的有限集合,内存是线性连续的。
一维数组:数组中每个元素都只带有一个下标;
二维数组:数组中每个元素带有两个下标;
………………
N维数组:数组中每个元素带有N个下标。
<data_type>[] variable_name;
2. 数组的使用
int[] array; // 数组的声明,并没有分配内存
int[] array1 = new int[5]; // 数组的声明并分配内存
int iNumber = 10;
// 第一种数组初始化
int[] array3 = new int[5];
for(int i = 0; i < array3.Length; i++)
{
array3[i] = iNumber;
iNumber += 10;
}
Debug.Log("访问第4个元素(第三个下标)代表的数据:" + array3[3]);
array3[3] = 400;
Debug.Log("访问第4个元素(修正)代表的数据:" + array3[3]);
// 第二种数组初始化
int[] array4 = new int[5] { 100, 200, 300, 400, 500 };// 容量显式声明
int[] array5 = new int[] { 100, 200, 300, 400, 500 };// 容量隐式声明
// 第三种数组初始化
int[] array6 = { 100, 200, 300, 400, 500 };
Debug.Log("获取array6的数组长度(容量)= " + array6.Length);
// 二维数组
int[,] array7 = new int[2, 2];
array7[0, 0] = 100;// 1行1列
array7[0, 1] = 200;// 1行2列
array7[1, 0] = 300;// 2行1列
array7[1, 1] = 400;// 2行2列
Debug.Log("打印第2行第1列数据:" + array7[1, 0]);
int[,] array8 = new int[2, 2]
{
{ 1000, 2000 },
{ 3000, 4000 },
};
int[,] array9;
array9 = new int[2, 3]
{
{ 1000, 2000, 9 },
{ 3000, 4000, 8 },
};
Debug.Log("array9总长度(容量)" + array9.Length);
Debug.Log("array9行数" + array9.GetLength(0));
Debug.Log("array9列数" + array9.GetLength(1));
// 三维数组
int[,,] array10 = new