150 likes | 305 Views
定义类的方法成员. 类的方法成员. 方法指类中对数据进行某种处理操作的算法(函数). class 类名 { [ 方法修饰符] 返回数据类型 方法名( [形式参数表] ) { } }. class Math { public double Multiply( double a, double b ) { return a*b; } }. 带参数的方法. 类的方法成员. 值类型参数 引用型参数 ( ref) 输出型参数 ( out) 数组型参数 ( params).
E N D
定义类的方法成员 类的方法成员 • 方法指类中对数据进行某种处理操作的算法(函数) class 类名 { [方法修饰符] 返回数据类型 方法名( [形式参数表] ) { } } class Math { publicdouble Multiply( double a,double b) { return a*b; } }
带参数的方法 类的方法成员 • 值类型参数 • 引用型参数 (ref) • 输出型参数 (out) • 数组型参数 (params)
引用型参数 (ref) 类的方法成员 • 向方法传递的是实参的地址 protected void swap(ref int x,ref int y){ int temp=x; x=y y=temp; } • 调用方法 int a=5,b=10; app.swap(ref a,ref b);
输出型参数 (out) 类的方法成员 • 用于从方法返回数据 public string OutTest(out string i) { i="im a studnet"; return "you are a teacher"; } p.OutTest(out x);
数组型参数 (params) 类的方法成员 • 表示方法的形参个数不固定 • 必须是一维数组 • 必须是形参表中最后一个参数 • Main()方法的参数
方法重载 类的方法成员 • 功能相同而参数不同的方法可以使用相同的方法名 public int IPrint(int){…} public double DPrint(double ){…} public string SPrint(string){…} public int Print(int){…} public double Print(double ){…} public string Print(string){…}
递归方法 类的方法成员 • 在类中实现递归调用,解决如阶乘、汉诺塔问题 public long Factorial(long n) { if(n==0||n==1) return 1; else return n*Factorial(n-1); }
数组的概念 • 掌握定义和初始化数组的方法 • 掌握访问数组的方法 • 熟练使用System.Array类的属性和方法
一维数组的定义和初始化 一维数组 • 数组类型[ ] 数组名 ; 先定义 后使用 int [ ]arry; decimal [ ] balance; • 静态初始化 int [ ]arry ={1,2,3,4}; string [ ]str= {“china”,”American”,”Korea”}; • 动态初始化 (可动态修改数组长度) int [ ]arry ; arry = new int [10];
引用一维数组元素 一维数组 • 数组名 [下标]; int [ ]arry ={1,2,3,4}; arry[i]; • 冒泡法排序 • foreach循环访问数组
二维数组的定义和初始化 二维数组 • 数组类型[ ,] 数组名 ; 先定义 后使用 int [ ,]arry; decimal [ ,] balance; • 静态初始化 int [ ,]arry ={{1,2} ,{3,4}}; • 动态初始化 (可动态修改数组长度) int [ ,]arry= new int [10,10];
引用二维数组元素 二维数组 • 数组名 [下标1,下标2]; arry[i,j]; • 矩阵相乘 • 分行输出
不规则数组的定义和初始化 不规则数组 • 数组类型[ ] [ ] 数组名 ; 先定义 后使用 int [ ][ ]arry; string [ ][ ]balance; • 初始化 int [ ][ ]arry = new int [10][ ]; arry [0] =new int[]{1,2,3,4}; arry [1] =new int[]{1,2,3,4,5,6};
引用不规则数组元素 不规则数组 • 数组名 [下标1] [下标2]; arry[i] [j]; • 杨辉三角形
System.Array类的使用 System.Array类 • Array类 • Array成员 • 静态方法,可直接调用 • 参考MSDN