文章目录
程序流程控制
foreach
语法格式为:
foreach(类型 标识符 in 集合)
{
循环代码
}
例子如下:通过foreach循环长出字符数组0和1的个数并输出
int x = 0, y = 0;
char[] ch = new char[] { '0', '1', '0', '1', '1', '1', '0', '0', '1', '0', '0' };
Console.WriteLine(ch);
foreach (char a in ch)
{
if(a=='0')
{
x++;
}
else
{
y++;
}
}
Console.WriteLine("0的个数为:{0}\t1的个数为:{1}", x, y);
Console.ReadLine();
goto
goto是跳转到的意思。但是建议少用,因为它会使代码的可读性下降
int i = 5;
goto tab;
i = 100;
tab: Console.WriteLine(i);//goto直接转到tab,不执行i=100
数组
创建数组
创建一维数组
声明一维数组:dadatype[] arrayname;
1.在声明数组时为数组的元素赋初值
int[] myarry = { 5, 9, 15, 22, 30 };
string[] mystrarr = { "diagram", "cat", "dog" };
2.在声明数组时指定数组大小,用new关键字
int[] myarray = new int[4];//用new关键字为它分配内存空间
或者
const int size = 5;
int[] myarray = new int[size];
3.赋值
声明数组时同时给数组赋值:
int[] myarry = { 5, 9, 15, 22, 30 };
string[] mystrarr = { "diagram", "cat", "dog" };
使用索引号赋值给一个单独的数组元素:
int[] a = new int[10];
a[3] = 8;
4.创建并初始化一个数组
int[] a = new int[5] { 29, 28, 22, 27, 25 };
5.也可以忽略数组大小
int[] a = new int[] { 20, 20, 10, 45 };
6.利用数组进行赋值
int[] x = new int[] { 5, 10, 15 };
int[] y = x;
创建二维数组
1.声明数组时为数组的元素赋值
int[,] a = { { 3, 4 },{ 5, 6 } };
2.使用new创建
int[,] a = new int[2, 2] { { 1, 2 }, { 3, 4 } };
3.也可以不限定行数和列数
int[,] a = new int[,] { { 1, 2 }, { 3, 4 } };
4.二维数组的赋值
int[,] a = new int[3, 4]
{
{1,2,3,4 },
{5,6,7,8 },
{9,10,11,12 }
};
创建动态二维数组
int x = 2;
int y = 3;
int[,] array = new int[x, y];
Console.WriteLine("请输入动态二维数组的行数:");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入动态二维数组的列数:");
int y = Convert.ToInt32(Console.ReadLine());
int[,] array = new int[x, y];
Console.WriteLine("遍历数组如下:");
for(int i=0;i<x;i++)
{
for(int j=0;j<y;j++)
{
Console.Write(i + j.ToString() + " ");
}
Console.WriteLine();
}
创建多维数组
int[,,] a = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } } };
int[,,] a2 = new int[2, 2, 2] { { { 1, 2 }, { 3, 4 } }, {{ 5, 6 }, { 7, 8 } } };
创建交错数组
交错数组的特点是数组中的每一行的长度并不相同
1.
int[][] array= new int[4][];
2.对交错数组每行进行初始化
int[][] array= new int[4][];//每一行都是一个一维数组
array[0] = new int[5];
array[1] = new int[4];
array[2] = new int[3];
array[3] = new int[2];
3.索引赋值法,给单个元素赋值
int[][] array= new int[4][];
array[1][0] = 1;
array[2][1] = 2;
4.直接给交错数组赋初值
int[][] array= new int[4][];
array[0] = new int[] { 1, 3, 5, 32 };
array[1] = new int[] { 2, 3, 4 };
array[2] = new int[] { 9 };
array[3] = new int[] { 3, 5 };
5.声明数组时将其初始化
int[][] a = new int[][]
{
new int[]{1,3,5,7},
new int[]{2,4},
new int[]{9,11}
};
数组应用
一维数组的使用
1.对数组进行访问
int[] a = new int[5];
for(int i=0;i<5;i++)//利用for进行访问
{
a[i] = i * 5;
}
for(int j=0;j<5;j++)
{
Console.WriteLine("第{0}个元素为{1}", j + 1, a[j]);
}
利用foreach访问
int[] array = { 5, 10, 15, 20, 25 };
foreach(int num in array)
{
Console.WriteLine("数组元素为:{0}", num);
}
二维数组的使用
- 使用下标进行赋值
a[2, 1] = 5;
- 对二维数组进行遍历
利用for进行数组遍历
int[,] a = new int[3, 4]
{
{1,2,3,4 },
{5,6,7,8 },
{9,10,11,12 }
};
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
{
Console.WriteLine("a[{0},{1}]={2}", i , j , a[i, j]);
}
}
利用foreach进行遍历
int[,] a = new int[3, 4]
{ {1,2,3,4},
{5,6,7,8 },
{ 9,10,11,12}
};
Console.WriteLine("数组元素为:");
foreach(int i in a)
{
Console.WriteLine("{0}", i);
}
多维数组的使用
多维数组的遍历:
int[,,] a = new int[,,]
{
{{1,2},{3,4 } },
{{5,6},{ 7,8} },
{{9,10},{11,12} }
};
for(int i=0;i<3;i++)
{
for(int j=0;j<2;j++)
{
for(int k=0;k<2;k++)
{
Console.Write("a[{0}][{1}][{2}]={3}\t", i, j, k, a[i, j, k]);
}
Console.WriteLine();
}
Console.WriteLine();
}
交错数组的使用
使用foreach对数组进行初始化
int[][] array = new int[4][];
array[0] = new int[] { 1, 3, 5, 32 };
array[1] = new int[] { 2, 3, 4 };
array[2] = new int[] { 9 };
array[3] = new int[] { 3, 5 };
foreach(int[] i in array)
{
foreach(int j in i)
{
Console.Write("{0} ", j);
}
Console.WriteLine();
}
传递数组给函数
首先定义一个静态的double类型的方法getaverage。
public static double getaverage(int[] arr,int size)
{
double avg = 0;
double sum = 0;
for(int i=0;i<size;i++)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}
static void Main(string[] args)
{
int[] arr = new int[] { 1, 2, 3, 4, 5 };
double avg;
avg = getaverage(arr, 5);
Console.WriteLine("数组的平均值为: {0}", avg);
Console.ReadLine();
}
参数数组
当声明一个方法时,用户不能确定要传递给函数作为参数的参数数目。参数数组解决了这个问题。参数数组通常用于传递未知数量的参数给函数。参数数组通过关键字params定义。
Array类
C#中的数组是由System.Array类派生而来的引用对象,可以用Array类的属性对数组进行操作。
Array类的属性
IsFixedSize
IsReadOnly
Lenght
LongLength
Rank
int[] array = new int[5];
for(int x=1;x<5;x++)
{
array[x - 1] = x;
}
Console.WriteLine("显示数组中的数据:");
for(int i=0;i<5;i++)
{
Console.Write("{0} ", array[i]);
}
Console.WriteLine("\n");
Console.WriteLine("数组是否只有固定大小: " + array.IsFixedSize);
Console.WriteLine("数组是否只读: " + array.IsReadOnly);//是否只读
Console.WriteLine("数组的长度:" + array.Length);
Console.WriteLine("数组的长度为: " + array.LongLength);
Console.WriteLine("数组的维度为: " + array.Rank);
Console.ReadLine();
Array类的方法
Clear
Copy
CopyTo
GetLength
GetLongLength
tostring
等
string[,] student = { { "张三","二班"},{"李四","四班" },{"王五","五班" },{"王明","六班" },{"李华","未知" } };
Console.WriteLine("以下为正序输出: ");
for(int i=0;i<5;i++)
{
for (int j = 0; j < 2; j++)
{
Console.Write(student[i, j]+"\t");
}
Console.WriteLine();
}
Console.WriteLine("以下为逆序输出: ");
for(int i=4;i>=0;i--)
{
for(int j=1;j>=0;j--)
{
Console.Write(student[i, j] + "\t");
}
Console.WriteLine();
}
Console.WriteLine("以下为Length属性:数组包含元素的总个数");
Console.WriteLine(student.Length);
//获取数组中指定维度的下界
Console.WriteLine(student.GetLowerBound(0));
//获取数组中指定维度的上界
Console.WriteLine(student.GetUpperBound(0));
查找数组元素
IndexOf方法可以查找元素首次出现的位置,LastIndexOf为元素最后一次出现的位置。元素位置为从0开始的索引值。
int[] array = { 9, 11, 4, 5, 8, 9, 22, 4, 5, 6, 7, 8, 9 };
int first = 0, last = 0;
first = Array.IndexOf(array, 9);
last = Array.LastIndexOf(array, 9);
if(first<0)
{
Console.WriteLine("没有找到元素9");
}
else
{
Console.WriteLine("找到元素9");
Console.WriteLine("该元素第一次出现的索引为:{0},该元素第二次出现的索引为{1}", Array.IndexOf(array,9),Array.LastIndexOf(array,9));
}
数组排序
Arraylz提供两种方法Sort和Reverse用于数组排序
int[] array = { 11, 5, 89, 17, 20, 63, 12, 18, 9, 29, 37, 14 };
Console.WriteLine("原数组为: ");
foreach(int i in array )
{
Console.Write(i + " ");
}
Console.WriteLine();
//利用sort进行排序,升序排序
Console.WriteLine("数组实现升序以后:");
Array.Sort(array);
foreach (int i in array)
{
Console.Write(i + " ");
}
Console.WriteLine();
//利用Reverse实现降序,并且更改数组的存储位置
Array.Reverse(array);
Console.WriteLine("数组实现降序以后:");
foreach(int i in array)
{
Console.Write(i + " ");
}
数组的合并与拆分
数组的拆分与合并不是针对一个数组进行操作,而是将两个数组合并到第三个数组中。
数组的拆分换合并通过Array类的copy方法实现的。
int[] arr1 = { 9, 1, 2, 3, 4, 5, 6, 7, 8 };
int[] arr2 = { 11, 12, 13, 14, 15, 16, 17, 18, 19 };
Console.WriteLine("原数组arr1为: ");
foreach(int i in arr1)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.WriteLine("原数组arr2为: \n");
foreach(int i in arr2)
{
Console.Write(i + " ");
}
Console.WriteLine("合并数组arr1和arr2\n");
int[] newarr = new int[18];
Array.Copy(arr1, newarr, 9);//将arr1的数组从0开始取9个元素,放入newarr中
Array.Copy(arr2, 0, newarr,9, 9);//数组arr2索引值从0开始取9个长度,放入newarr,并从索引值9开始存放
foreach (int i in newarr)
{
Console.Write(i + " ");
}
Console.WriteLine("\n拆分数组的结果");
int[] newarr2 = new int[5];
Array.Copy(newarr, 11, newarr2, 0, 5);//newarr数组索引值从11开始取5个元素,放到newarr2中,从索引值0开始存放
foreach(int i in newarr2)
{
Console.Write(i + " ");
}
Console.WriteLine();
面向对象部分
方法
传递参数
1.按值参数传递
public void method(int x)
{
x *= x;
Console.WriteLine("method方法内的值为 : {0}", x);
}
static void Main(string[] args)
{
Program n = new Program();
int x = 9;
Console.WriteLine("调用method方法之前的值为: {0}", x);
n.method(x);
Console.WriteLine("调用method方法之后的值: {0}", x);
Console.ReadLine();
}
2.按照引用参数传递
该方式就是对变量内存位置的引用。引用参数与提供给方法的实际参数具有相同的内存位置,在c#中,使用ref关键字声明引用参数。
public void Method(ref int x)//传递的不是y的值,而是传递y的引用,也就是变量y在内存中的地址。
{
x *= x;
Console.WriteLine("Method方法内部的值为: {0}", x);
}
static void Main(string[] args)
{
Program n = new Program();
int y = 7;
Console.WriteLine("Main方法内部的值为: {0}", y);
n.Method(ref y);
Console.WriteLine("通过引用传递变量: {0}", y);
Console.ReadLine();
}
结果如下:
Main方法内部的值为: 7
Method方法内部的值为: 49
通过引用传递变量: 49
3.按照输出参数传递
输出参数时用out修饰符声明的
static int Maxnum(int[] arr,out int num)
{
int max = arr[0];
num = 0;
for(int i=0;i<arr.Length;i++)
{
if(arr[i]>max)
{
max = arr[i];
num = i;
}
}
return max;
}
static void Main(string[] args)
{
int[] arr = { 12, 4, 567, 3, 9, 6, 8 };
int max=0;
Console.WriteLine("数组arr最大的元素值为{0},其索引值为{1}",Maxnum(arr,out max),max);
Console.ReadLine();
}
若要使用out参数,方法定义和调用方法必须显式使用out关键字
4.按照参数数组传递
对于不能确定要传递的参数个数时,可使用params关键字来定义
static int Add(params int[] arr)
{
int sum = 0;
foreach(int i in arr)
{
sum += i;
}
return sum;
}
static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Console.WriteLine("arr数组中所有元素的和为: {0}",Add(arr));
Console.ReadLine();
}
方法的分类
1.静态方法
静态方法不对特定实例进行操作,并且只能访问类中的静态成员。而且不能使用实例成员。访问静态方法时可以直接访问,也可以使用类名而不需要创建对象,也不能使用对象名来引用。
2.实例方法
实例方法对特定实例进行操作,并且能够访问静态方法和实例成员。在调用实例方法的实例上,可以通过this显式访问该实例。但是在静态方法中引用this是错误的。
3.外部方法
外部方法是在外部实现的。
class Program
{
[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type);
static int Main(string[] args)
{
Console.WriteLine("请输入您的姓名: ");
string name = Console.ReadLine();
return MessageBox(0, "您好: " + name + "\n\n" + "欢迎学习C#", "信息提示", 0);
Console.ReadLine();
}
}
类与对象
对象实例化
enum Gender
{
男,
女
}
class Clerk
{
public string name;
public Gender gender;
public int age;
public string department;
public int workyears;
public void write()
{
Console.WriteLine("我叫{0},性别{1},年龄{2},在{3}任职,工作年限为{4}年", name, gender, age, department, workyears);
}
}
class Program
{
static void Main(string[] args)
{
Clerk zs = new Clerk();
zs.name = "张三";
zs.gender = Gender.男;
zs.age = 25;
zs.department = "人力部";
zs.workyears = 5;
zs.write();
Clerk ls = new Clerk();
ls.name = "李四";
ls.gender = Gender.女;
ls.age = 13;
ls.department = "财务部";
ls.workyears = 1;
ls.write();
Console.ReadLine();
}
}
class Clerk
{
private string name="张三";
private int age;
public int Age
{
get
{
return age;
}
set
{
if(value<18||value>60)//对输入的年龄进行限定
{
value = 0;
}
age = value;
}
}
private char gender;
public char Gender
{
get
{
if(gender=='男'||gender=='女')
{
gender = '男';
}
return gender;
}
set
{
gender = value;
}
}
public void Write()
{
Console.WriteLine("新入职员工: \n姓名:{0}\t年龄: {1}\t性别: {2}", name, age, gender);
}
}
class Program
{
static void Main(string[] args)
{
Clerk n = new Clerk();
n.Age = 66;
n.Gender = '女';
n.Write();
Console.WriteLine("修改员工信息");
n.Age = 45;
n.Write();
Console.ReadLine();
}
}
通过get访问器,返回私有字段age,和私有字段gender的值。get访问器必须用return或者throw语句结尾。
set访问器类似于返回void的方法。如:
set
{
gender = value;
}
分部类与方法
public partial class Program
{
partial void Write();//分部方法的声明
partial void Write()//分部方法的实现
{
Console.WriteLine("这是一个分部方法");
}
}
public partial class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Write();
Console.ReadLine();
}
}
虚方法和重写方法
若一个实例方法的声明中含有virtual修饰符,称该方法为虚方法。
class myclass1
{
public virtual void virtualmethod()
{
Console.WriteLine("这是一个虚方法");
}
public void notvirtualmethod()
{
Console.WriteLine("这是一个非虚方法");
}
}
class myclass2:myclass1//使myclass2继承于myclass1
{
public override void virtualmethod()//override对虚方法进行重写,重写的前提是声明为virtual或者abstract类型
{
Console.WriteLine("这是一个新的虚方法");
}
public new void notvirtualmethod()
{
Console.WriteLine("这是一个新的非虚方法");
}
}
class Program
{
static void Main(string[] args)
{
myclass1 c1 = new myclass1();
c1.virtualmethod();
c1.notvirtualmethod();
myclass2 c2 = new myclass2();
c2.virtualmethod();
c2.notvirtualmethod();
c1 = c2;
c1.virtualmethod();
c1.notvirtualmethod();
Console.ReadLine();
}
class myclass1
{
public virtual void Write()
{
Console.WriteLine("这是一个虚方法,可以被重写");
}
}
class myclass2:myclass1//使myclass2继承于myclass1
{
public override sealed void Write()//override对虚方法进行重写,重写的前提是声明为virtual或者abstract类型
{
Console.WriteLine("这是一个重写的方法,被称为已经重写了的基方法");
}
}
class Program
{
static void Main(string[] args)
{
myclass1 c1 = new myclass1();
c1.Write();
myclass1 c2 = new myclass2();
c2.Write();
Console.ReadLine();
}
}
继承的特性
class clerk
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
private string department;
public string Department
{
get
{
return department;
}
set
{
department = value;
}
}
public void CSeyHello()
{
Console.WriteLine("大家好,我是{0}的{1}", Department, Name);
}
}
class Sales:clerk
{
private int salestarget;
public int Salestarget
{
get
{
return salestarget;
}
set
{
salestarget = value;
}
}
public void SSayHello()
{
Console.WriteLine("大家好,我是{0}的{1},我的销售目标为{2}元", Department, Name, Salestarget);
}
}
class Technicalsupport:clerk
{
private double satisfactionrate;
public double Satisfactionrate
{
get
{
return satisfactionrate;
}
set
{
satisfactionrate = value;
}
}
public void TSSayHello()
{
Console.WriteLine("大家好,我是{0}的{1},我的服务满意度为{2}分", Department, Name, Satisfactionrate);
}
}
class Program
{
static void Main(string[] args)
{
clerk zs = new clerk();
zs.Name = "张三";
zs.Department = "人力部";
zs.CSeyHello();
Sales ls = new Sales();
ls.Name = "李四";
ls.Department = "销售部";
ls.Salestarget = 5000;
ls.SSayHello();
Technicalsupport zh = new Technicalsupport();
zh.Name = "周红";
zh.Department = "技术支持部";
zh.Satisfactionrate = 9.8;
zh.TSSayHello();
Console.ReadLine();
}
}