文档详情

Csharp面向对象编程.ppt

发布:2018-05-05约3.39千字共16页下载文档
文本预览下载声明
第四章 类和对象(二) 回顾 面向对象语言特点:封装、继承、多态 访问修饰符的语法和作用:public和private 值类型和引用类型的区别 值类型数据和引用类型数据之间的转换:装箱和拆箱 本章目标 静态方法和静态成员变量 ref关键字的使用 掌握out关键字 掌握重载的语法和意义 ref关键字4-1 回顾上一章值类型做方法参数,不能保存修改后的数据 static void Main(string[ ] args) { int num1 = 5, num2 = 10; // 两个数字 Console.WriteLine(交换前两个数的值分别为:{0}和{1}, num1, num2); Swap(num1, num2); // 交换两个数的值 Console.WriteLine(交换后两个数的值分别为:{0}和{1}, num1, num2); } // 交换两个数的方法 private static void Swap(int num1, int num2) { int temp; // 中间变量 temp = num1; num1 = num2; num2 = temp; } 值传递不能保留参数的修改 要按引用传递,使用 ref ref关键字4-2 如果需要值类型参数保存修改后的结果,就需要使用ref关键字,将值类型按引用方式传递 ref 修饰参数: 调用方法后,参数值的更改仍然保留 定义和调用 在参数前使用ref 在调用方法前 作为参数的变量声明并赋值 何时使用 希望保留参数的更改 ref关键字4-3 static void Main(string[ ] args) { Console.WriteLine(交换前两个数的值分别为:{0}和{1}, num1, num2); // 交换两个数的值 Swap(ref num1, ref num2); Console.WriteLine(交换后两个数的值分别为:{0}和{1}, num1, num2); } // 交换两个数的方法 private static void Swap(ref int num1, ref int num2) { int temp; // 中间变量 temp = num1; num1 = num2; num2 = temp; } 调用时也要使用 ref ref关键字4-4 调用方法 方法定义 ModifyValue( num1, ref num2); ModifyValue( int param1, ref int param2){ }; 调用前 num1=3 num2=5 param1=3 param2=5 方法中修改: 调用后 param1=4 param2=6 num1=3 num2=6 调用 值传递 引用传递 out关键字 ref 参数的变量必须最先初始化。而out则不同,out的参数在传递之前不需要初始化。 private static void AddScore(ref int score,out int scoreResult) { if (score 50 score 60) { Console.WriteLine(你的成绩在50-60之间,可以加分。); score = 60; scoreResult = 60; } } 都可以输出结果 ref侧重修改,out侧重输出 不能写成AddScore(out int scoreResult) int score =55; int scoreResult; AddScore(ref score,out scoreResult); 静态方法——static关键字 class mySwap { public static void Swap(ref int num1,ref int num2) { int temp; temp = num1; num1 = num2; num2 = temp; } } class Program { static void Main(string[] args) { int num1 = 5, num2 = 10; mySwap.Swap(ref num1, ref num2); } } 回顾一下,S
显示全部
相似文档