精品ppt课件清华大学原版c#学习资料第7章类加.pptVIP

  • 3
  • 0
  • 约1.16万字
  • 约 54页
  • 2016-09-25 发布于湖北
  • 举报

精品ppt课件清华大学原版c#学习资料第7章类加.ppt

精品ppt课件清华大学原版c#学习资料第7章类加.ppt

引用型参数 引用型参数和值参不同,引用型参数并不会开辟新的内存区域。 当利用引用型参数向方法传递形参时,编译程序将把实际值在内存中的地址传递给方法。 引用型参数一般是两种情况下存在 方法的形参本身就是引用类型。 参见示例7.8 通过声明ref关键字使参数按引用传递 参见示例7.9 using System; class RefValueParamSample { static void Swap(ref int x, ref int y) { int temp = x; x = y; y = temp; } static void Main() { int i = 1, j = 2; Swap(ref i, ref j); Console.WriteLine(i = {0}, j = {1}, i, j); } } 输出参数 与引用型参数类似,输出型参数也不开辟新的内存区域。 与引用型参数的差别在于,调用方法前无需对变量进行初始化。 输出型参数用于传递方法返回的数据。 out 修饰符后应跟随与形参的类型相同的类型声明 例:static void SplitPath(string path, out string dir, out string name){…..} 示例参见书中例7.10 using System; class OutSample { static void SplitPath(string path, out string dir, out string name) { int i = path.Length; while (i 0) { char ch = path[i - 1];//最后一个字符 if (ch == ‘\\’ || ch == ‘/’ || ch == ‘:’) break;//是反斜杠分割 i--; } dir = path.Substring(0, i);//0—i-1是目录 name = path.Substring(i);//从i—最后 } static void Main() { string dir, name; SplitPath(c:\\Windows\\System\\hello.txt, out dir, out name); Console.WriteLine(dir); Console.WriteLine(name); } }//形参和实参共用一个内存, 数组型参数 形参表中包含了数组型参数,那么它必须在参数表中位于最后。 params关键字可以指定在参数数目可变处采用参数的方法参数。 在方法声明中的 params关键字之后不允许任何其他参数 在方法声明中只允许一个 params 关键字。 示例参见书中例7.11 using System; class ParamsSample { static void F(params int[] args) { Console.Write(Array contains {0} elements:, args.Length); foreach (int i in args) Console.Write( {0}, i); Console.WriteLine(); } public static void Main() { int[] a = { 1, 2, 3 }; F(a); F(10, 20, 30, 40); F(); } } this 关键字 this仅限于在构造函数、类的方法和类的实例中使用。 在类的构造函数中出现的this作为一个值类型,它表示对正在构造的对象本身的引用。 在类的方法中出现的this作为一个值类型,它表示对调用该方法的对象的引用。 在结构的构造函数中出现的this作为一个变量类型,它表示对正在构造的结构的引用。 在结构的方法中出现的this作为一个变量类型,它表示对调用该方法的结构的引用。 经常在构造函数或者类方法中,如果传入参数和类字段同名,一定需在类字段前加上this。 this示例 using

文档评论(0)

1亿VIP精品文档

相关文档