《NET程序设计》教学课件_第1页
《NET程序设计》教学课件_第2页
《NET程序设计》教学课件_第3页
《NET程序设计》教学课件_第4页
《NET程序设计》教学课件_第5页
已阅读5页,还剩239页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、.NET 程序设计C# 编程语言(3.0)陈伟(陈俊先)第1页,共244页。自我介绍从1994年做管理软件从2001年使用.NET和C#主要工作:俊先管理软件开发平台.Net软件设计新思维像搭积木一样搭建软件俊先管理软件开发平台总体架构第2页,共244页。商务新星.NETC#源码30万行第3页,共244页。.NET 的内容ConsoleWindows FormsADO.NETASP.NETWeb ServiceXMLLINQ (LINQ to object、LINQ to SQL、LINQ to DataSet、LINQ to XML)Windows Presentation Foundati

2、on (WPF)Windows Communication Foundation (WCF)Windows Workflow Foundation (WF)Windows CardSpaceSilverlight 3.0 ASP.NET 3.5 ExtensionsBlend。第4页,共244页。C#与.NET的关系第5页,共244页。Hello World - 您的第一个程序 using System;/ A Hello World! program in C#namespace HelloWorld class Hello static void Main() System.Console

3、.WriteLine(Hello World!); 第6页,共244页。Main() 和命令行参数 class CommandLine2 static void Main(string args) System.Console.WriteLine(Number of command line parameters = 0, args.Length); foreach (string s in args) System.Console.WriteLine(s); Number of command line parameters = 3JohnPaulMary第7页,共244页。类型第8页,共2

4、44页。数据类型值类型简单类型结构类型枚举类型引用类型类接口委托(代理)数组第9页,共244页。值类型结构类型:struct PhoneBook public string name; public string phone; public string address;PhoneBook pb; = “wang”;pb.phone = “88102324”;pb.address = “青年大街126号”;第10页,共244页。值类型枚举类型:用户定义的整数(int、short、long、byte)enum WeekDay Sunday, Monday, Tuesday, Wednesday,

5、 Thursday, Friday, Satursay ;WeekDay wd;wd = WeekDay.Monday;第11页,共244页。类型转换隐式数值类型转换:自动转换成高精度的数值int i = 5;int j = 8;long = i + j;sbyeshort、int、long、float、double、decimalbyteshort、ushort、int、uint、long、ulong、float、double、decimalshortint、long、float、double、decimalushortint、uint、long、ulong、float、double、dec

6、imalintlong、float、double、decimaluintlong、ulong、float、double、decimallongfloat、double、decimalulongfloat、double、decimalfloatdoublecharushort、int、uint、long、ulong、float、double、decimal第12页,共244页。类型转换隐式引用类型转换:任何对象可以转换为object派生类(接口)可以转换为父类(接口) 任何数组类型可以转换为System.Array任何委托(代理)类型可以转换为System.Delegate任何数组类型可以转换为

7、System.ICloneablenull类型可以可以转换为任何引用类型第13页,共244页。类型转换显式数值转换int i = 10;int j = 30;long l = (long)(i + j);int g = (int)l;第14页,共244页。装箱(Boxing)与拆箱(Unboxing)装箱转换(Boxing):把值类型转换为object类型或接口类型int I = 10;object obj = i;拆箱转换(Unboxing):把对象类型或接口类型转换为值类型int i = 10;object obj = i;int j = (int)obj;第15页,共244页。类型转换类

8、ConvertSampleCSharpConvertConvert第16页,共244页。数组/ Single-dimensional arrays. int myArray1 = new int 5; string myArray2 = new string6; / Multidimensional arrays. int, myArray3 = new int4,2; 第17页,共244页。初始化数组 / Single-dimensional array (numbers).int n1 = new int4 2, 4, 6, 8;int n2 = new int 2, 4, 6, 8;in

9、t n3 = 2, 4, 6, 8;/ Single-dimensional array (strings).string s1 = new string3 John, Paul, Mary;string s2 = new string John, Paul, Mary;string s3 = John, Paul, Mary;/ Multidimensional , n4 = new int3, 2 1, 2, 3, 4, 5, 6 ;int, n5 = new int, 1, 2, 3, 4, 5, 6 ;int, n6 = 1, 2, 3, 4, 5, 6 ;/ Jag

10、ged n7 = new int2 new int 2,4,6, new int 1,3,5,7,9 ;int n8 = new int new int 2,4,6, new int 1,3,5,7,9 ;int n9 = new int 2,4,6, new int 1,3,5,7,9 ;第18页,共244页。字符串string s1 = Hello;string s2 = s1;s1 += and goodbye.;Console.WriteLine(s2); /outputs Hello第19页,共244页。字符串原义字符串: 符号 符号会告知字符串构造函数忽略转义符

11、和分行符。因此,以下两个字符串是完全相同的:string p1 = My DocumentsMy Files;string p2 = My DocumentsMy Files;第20页,共244页。字符串访问各个字符string s4 = Hello, World;char arr = s4.ToCharArray(0, s4.Length);foreach (char c in arr) System.Console.Write(c); / outputs Hello, World第21页,共244页。字符串将字符串拆分为子字符串 使用 Split 方法分析字符串class TestStri

12、ngSplit static void Main() char delimiterChars = , , ., :, t ; string text = onettwo three:four,five six seven; System.Console.WriteLine(Original text: 0, text); string words = text.Split(delimiterChars); System.Console.WriteLine(0 words in text:, words.Length); foreach (string s in words) System.Co

13、nsole.WriteLine(s); 第22页,共244页。字符串StartsWith()EndWith()IndexOf()Trim()ToLower()Substring()练习应用这些方法自己做一些小程序第23页,共244页。字符串class StringSearch static void Main() string str = Extension methods have all the capabilities of regular static methods.; / Write the string and include the quotation marks System

14、.Console.WriteLine(0,str); bool test1 = str.StartsWith(extension); System.Console.WriteLine(starts with extension? 0, test1); bool test2 = str.StartsWith(extension, System.StringComparison.OrdinalIgnoreCase); System.Console.WriteLine(starts with extension? 0 (ignoring case), test2); bool test3 = str

15、.EndsWith(.); System.Console.WriteLine(ends with .? 0, test3); int first = str.IndexOf(method); int last = str.LastIndexOf(method); string str2 = str.Substring(first, last - first); System.Console.WriteLine(between two method words: 0, str2); / Keep the console window open in debug mode System.Conso

16、le.WriteLine(Press any key to exit.); System.Console.ReadKey(); 第24页,共244页。使用正则表达式搜索字符串 class TestRegularExpressions static void Main() string sentences = cow over the moon, Betsy the Cow, cowering in the corner, no match here ; string sPattern = cow; foreach (string s in sentences) System.Console.W

17、rite(0,24, s); if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase) System.Console.WriteLine( (match for 0 found), sPattern); else System.Console.WriteLine(); cow over the moon (match for cow found) Betsy the Cow (match for cow found)

18、cowering in the corner (match for cow found) no match here第25页,共244页。变量变量有7种:静态变量、实例变量、数组元素、值参数、引用参数、输出参数、局部变量class Apublic static int x;int y;Void F(int v, int a, ref int b, out int c) int i = 1;c = a + b+;其中,x是静态变量,y是实例变量,v0是数组元素,a是值参数,b是引用参数,c是输出参数,i是局部变量。第26页,共244页。变量的作用范围Void Main()for(i = 0; i

19、 0; i-)int j = 30;Console.WriteLine(I + j).ToString();第27页,共244页。变量的修饰符public:可以在任何地方访问proteced:可以在所属类及派生类中访问private:只能在所属类中访问第28页,共244页。运算符(操作符)第29页,共244页。只读变量与常量只读变量:只能在声明时或在构造方法中初始化。常量:只能在声明时初始化。class a public readlony int r = 10;const int c = 90;a()r = 30;第30页,共244页。特殊运算符(操作符)is:检查对象是否与特定的类型兼容。i

20、nt i = 10;if(i is object)Console.WriteLine(“i 是 object”);第31页,共244页。特殊运算符(操作符)as:转换为指定类型。as 运算符类似于强制转换操作。但是,如果无法进行转换,则 as 返回 null 而非引发异常。int i = 10;object obj = i as object;第32页,共244页。特殊运算符(操作符)typeof:获取原对象的类型第33页,共244页。特殊运算符(操作符)sizeof:用于获取 值类型 的字节大小。第34页,共244页。控制语句if语句switch语句第35页,共244页。循环语句while语

21、句dowhile语句for语句foreach语句第36页,共244页。foreach语句foreach循环可以在支持IEnumerable 接口容器中迭代每一个项目static void Main()int Ints = 1, 2, 3;foreach(int temp in Ints)Console.WriteLine(temp.ToString();第37页,共244页。跳转语句gotobreakcontinuereturn第38页,共244页。fixed 语句fixed 语句禁止垃圾回收器重定位可移动的变量。fixed 语句只能出现在不安全的上下文中。Fixed 还可用于创建固定大小的缓

22、冲区。fixed 语句设置指向托管变量的指针并在 statement 执行期间“钉住”该变量。如果没有 fixed 语句,则指向可移动托管变量的指针的作用很小,因为垃圾回收可能不可预知地重定位变量。C# 编译器只允许在 fixed 语句中分配指向托管变量的指针。第39页,共244页。fixed 语句class Point public int x, y; class FixedTest unsafe static void SquarePtrParam (int* p) *p *= *p; unsafe static void Main() Point pt = new Point(); pt

23、.x = 5; pt.y = 6; fixed (int* p = &pt.x) SquarePtrParam (p); Console.WriteLine (0 1, pt.x, pt.y); 第40页,共244页。lock 语句lock 关键字将语句块标记为临界区,方法是获取给定对象的互斥锁,执行语句,然后释放该锁。lock 关键字可确保当一个线程位于代码的临界区时,另一个线程不会进入该临界区。如果其他线程试图进入锁定的代码,则它将一直等待(即被阻止),直到该对象被释放。SamplesCSharpLockLockObject第41页,共244页。异常处理语句trycatchfinallyt

24、hrow第42页,共244页。习题1、使用 I/O 类列出某一目录下的所有文件名,并输出到标准控制台2、读文本文件(逐行),并输出到标准控制台;新建一个文件并向文件中写入字符串第43页,共244页。异常处理在应用程序遇到异常情况(如被零除情况或内存不足警告)时,就会产生异常。发生异常时,控制流立即跳转到关联的异常处理程序(如果存在)。如果给定异常没有异常处理程序,则程序将停止执行,并显示一条错误信息。可能导致异常的操作通过 try 关键字来执行。异常处理程序是在异常发生时执行的代码块。在 C# 中,catch 关键字用于定义异常处理程序。程序可以使用 throw 关键字显式地引发异常。异常对象

25、包含有关错误的详细信息,其中包括调用堆栈的状态以及有关错误的文本说明。即使引发了异常,finally 块中的代码也会执行,从而使程序可以释放资源。第44页,共244页。异常处理int top = 0, bottom = 0, result = 0;try result = top / bottom;catch (System.Exception ex) System.Console.WriteLine(0 exception caught here., ex.GetType().ToString(); System.Console.WriteLine(ex.Message);finally S

26、ystem.Console.WriteLine(Clean-up code executes here.);System.Console.WriteLine(Program execution continues here.);第45页,共244页。异常处理在 C# 中,程序中的运行时错误使用一种称为“异常”的机制在程序中传播。异常由遇到错误的代码引发,由能够更正错误的代码捕获。异常可由 .NET Framework 公共语言运行库 (CLR) 或由程序中的代码引发。一旦引发了一个异常,这个异常就会在调用堆栈中往上传播,直到找到针对它的 catch 语句。未捕获的异常由系统提供的通用异常处理程

27、序处理,该处理程序会显示一个对话框。异常由从 Exception 派生的类表示。private static void TestThrow() System.ApplicationException ex = new System.ApplicationException(Demonstration exception in TestThrow(); throw ex; 第46页,共244页。异常处理public static string GetTxtString(string strFileName)FileStream fs = null;StreamReader sr = null;s

28、tring strLine = ;string strTxt = ;tryfs = new FileStream (strFileName, FileMode.OpenOrCreate,FileAccess.Read);sr = new StreamReader(fs);strLine = sr.ReadLine();strLine = strLine.Trim();strTxt = strLine; catch(Exception e)throw e;finallyif(sr != null) sr.Close();if(fs != null) fs.Close();return strTx

29、t;第47页,共244页。异常处理引发异常之后,运行库检查当前语句以确定它是否在 try 块中。如果是,则检查与该 try 块关联的任何 catch 块,以确定它们是否能够捕获该异常。Catch 块通常会指定异常类型;如果该 catch 块的类型与异常或其基类的类型相同,则该 catch 块就能够处理该方法。如果引发异常的语句不在 try 块中,或者包含该语句的 try 块没有匹配的 catch 块,运行库将检查调用方法中是否有 try 语句和 catch 块。运行库将在调用堆栈中向上继续搜索兼容的 catch 块。在找到并执行 catch 块之后,控制权将传递给 catch 块之后的第一个语

30、句。在执行 catch 块之前,将检查运行库已评估过的 try 块(包括包含兼容的 catch 块的 try 块)中是否有 finally 块。Finally 块允许程序员清理中止的 try 块可能留下的任何不明确状态,或释放任何外部资源而不用等待运行库中的垃圾回收器来终结相关对象。 第48页,共244页。异常处理static void TestFinally() System.IO.FileStream file = null; System.IO.FileInfo fileInfo = new System.IO.FileInfo(C:file.txt); try file = fileI

31、nfo.OpenWrite(); file.WriteByte(0 xF); finally / Closing the file allows you to reopen it immediately - otherwise IOException is thrown. if (file != null) file.Close(); try file = fileInfo.OpenWrite(); System.Console.WriteLine(OpenWrite() succeeded); catch (System.IO.IOException) System.Console.Writ

32、eLine(OpenWrite() failed); 第49页,共244页。习题采用读文本文件,捕获异常第50页,共244页。类class Aclass B : A第51页,共244页。分部类可以将类、结构或接口的定义拆分到两个或多个源文件中。每个源文件包含类定义的一部分,编译应用程序时将把所有部分组合起来。若要拆分类定义,请使用 partial 关键字修饰符,如下所示: public partial class Employee public void DoWork() public partial class Employee public void GoToLunch() 第52页,共2

33、44页。分部类如果将任意部分声明为抽象的,则整个类型都被视为抽象的。如果将任意部分声明为密封的,则整个类型都被视为密封的。如果将任意部分声明为基类型,则整个类型都将继承该类。指定基类的所有部分必须一致,但忽略基类的部分仍继承该基类型。各个部分可以指定不同的基接口,最终类型将实现所有分部声明所列出的全部接口。在某一分部定义中声明的任何类、结构或接口成员可供所有其他部分使用。最终类型是所有部分在编译时的组合。第53页,共244页。分部类编译时将对分部类型定义的属性进行合并。例如,下面的声明: System.SerializableAttribute partial class Moon Syste

34、m.ObsoleteAttribute partial class Moon 等效System.SerializableAttributeSystem.ObsoleteAttributeclass Moon 第54页,共244页。分部类的限制要作为同一类型的各个部分的所有分部类型定义都必须使用 partial 进行修饰。 partial 修饰符只能出现在紧靠关键字 class、struct 或 interface 前面的位置。分部类型定义中允许使用嵌套的分部类型 。要成为同一类型的各个部分的所有分部类型定义都必须在同一程序集和同一模块(.exe 或 .dll 文件)中进行定义。分部定义不能跨越

35、多个模块。类名和泛型类型参数在所有的分部类型定义中都必须匹配。泛型类型可以是分部的。每个分部声明都必须以相同的顺序使用相同的参数名。下面的用于分部类型定义中的关键字是可选的,但是如果某关键字出现在一个分部类型定义中,则该关键字不能与在同一类型的其他分部定义中指定的关键字冲突: public 、private 、protected 、internal 、abstract 、sealed 基类new 修饰符(嵌套部分)第55页,共244页。分部类public partial class A public class A /错误partial class ClassWithNestedClass p

36、artial class NestedClass partial class ClassWithNestedClass partial class NestedClass 第56页,共244页。分部类示例:SampleCSharpPartialTypes第57页,共244页。分部方法分部方法在分部类型的一个部分中定义它的签名,并在该类型的另外一个部分中定义它的实现。partial class A partial void OnSomethingHappened(string s); partial class A partial void OnSomethingHappened(String

37、s) Console.WriteLine(Something happened: 0, s); 第58页,共244页。静态类类可以声明为static的,以指示它仅包含静态成员。不能使用 new 关键字创建静态类的实例。静态类在加载包含该类的程序或命名空间时由 .NET Framework 公共语言运行库 (CLR) 自动加载。它们仅包含静态成员。它们不能被实例化。它们是密封的,因此不可被继承。它们不能包含实例构造函数,但仍可声明静态构造函数以分配初始值或设置某个静态状态。 第59页,共244页。静态类public class Automobile public static int Numbe

38、rOfWheels = 4; public static int SizeOfGasTank get return 15; public static void Drive() public static event EventType RunOutOfGas; /other non-static fields and properties.第60页,共244页。类的成员字段(域)属性方法(函数)构造方法和析构方法索引指示器操作符事件第61页,共244页。字段(域)class A public readonly int x = 9;proteced float y;public static

39、string z = “123456789”;public string S;第62页,共244页。字段(域)静态字段(域):所有的实例共享非静态字段(域):每个实例有自己的副本static void Main()A a = new A();A b = new A();A.z = “abc”;b.S = A.z;Console.WriteLine(b.S);第63页,共244页。字段(域)的初始化对于值类型的字段自动初始化为默认值,对于引用类型的字段自动初始化为null。对于静态字段,在类加载时初始化;对于非静态字段,在创建实例时初始化。第64页,共244页。字段(域)的初始化class te

40、stpublic int x = 1;public int y = x + 1;/错误class testpublic static int x = 1;public int y = x + 1;/正确第65页,共244页。属性定义public class class1private string strvalue = “”;public string StrValuegetreturn strvalue;setIf(value != null)strvalue = value;第66页,共244页。存取属性static void Main()Class1 c1 = new Class1();

41、c1.StrValue = 12345;string b = c1.StrValue;Console.WriteLine(b);第67页,共244页。属性修饰符public:可以在任何地方访问proteced:可以在所属类及派生类中访问private:只能在所属类中访问static:静态属性只能访问类的静态成员virtual、override、abstract第68页,共244页。非对称访问器可访问性属性或索引器的 get 和 set 部分称为“访问器”。默认情况下,这些访问器具有相同的可见性或访问级别:其所属属性或索引器的可见性或访问级别。有关更多信息,请参见可访问性级别。不过,有时限制对其

42、中某个访问器的访问会很有用。通常是在保持 get 访问器可公开访问的情况下,限制 set 访问器的可访问性。 public string Name get return name; protected set name = value; 第69页,共244页。对访问器的访问修饰符的限制不能对接口或显式接口成员实现使用访问器修饰符。仅当属性或索引器同时具有 set 和 get 访问器时,才能使用访问器修饰符。这种情况下,只允许对其中一个访问器使用修饰符。如果属性或索引器具有 override 修饰符,则访问器修饰符必须与重写的访问器的访问器(如果有的话)匹配。访问器的可访问性级别必须比属性或索引

43、器本身的可访问性级别具有更严格的限制。第70页,共244页。自动实现的属性(3.0)当属性访问器中不需要其他逻辑时,自动实现的属性可使属性声明变得更加简洁。当您如下面的示例所示声明属性时,编译器将创建一个私有的匿名后备字段,该字段只能通过属性的 get 和 set 访问器进行访问。自动实现的属性必须同时声明 get 和 set 访问器。若要创建 readonly 自动实现属性,请给予它 private set 访问器。自动实现的属性 (Property) 不允许具有属性 (Attribute)。如果您必须在属性 (Property) 的后备字段上使用属性 (Attribute),则应该只创建常

44、规属性 (Property)。class LightweightCustomer public double TotalPurchases get; set; public string Name get; private set; / read-only public int CustomerID get; private set; / read-only第71页,共244页。属性示例SampleCSharpPropertyProperties第72页,共244页。属性练习定义一个类Employee,使期具有名字、年龄、性别(枚举)等属性,然后再去掉get或set,并PropertyGrid

45、观察各属性。第73页,共244页。属性 (特性)属性提供功能强大的方法以将声明信息与 C# 代码(类型、方法、属性等)相关联。一旦属性与程序实体关联,即可在运行时使用名为反射的技术对属性进行查询。属性具有以下特点:属性可向程序中添加元数据。元数据是嵌入程序中的信息,如编译器指令或数据描述。程序可以使用反射检查自己的元数据。通常使用属性与 COM 交互。第74页,共244页。属性 (特性)属性可以放置在几乎所有的声明中(但特定的属性可能限制在其上有效的声明类型)。在语法上,属性的指定方法为:将括在方括号中的属性名置于其适用的实体声明之前。所有属性名称都以单词“Attribute”结束,以便将它们

46、与“.NET Framework”中的其他项区分。但是,在代码中使用属性时不需要指定属性后缀。例如,DllImport 虽等效于 DllImportAttribute,但 DllImportAttribute 才是该属性在 .NET Framework 中的实际名称。ToolboxBitmap(typeof(Business.Controls.XPButton), XPButton.gif)public class XPButton : System.Windows.Forms.Button第75页,共244页。属性 (特性)创建C/C+联合System.Runtime.InteropServ

47、ices.StructLayout(LayoutKind.Explicit)struct TestExplicit System.Runtime.InteropServices.FieldOffset(0) public long lg; System.Runtime.InteropServices.FieldOffset(0) public int i1; System.Runtime.InteropServices.FieldOffset(4) public int i2; System.Runtime.InteropServices.FieldOffset(8) public doubl

48、e d; System.Runtime.InteropServices.FieldOffset(12) public char c; System.Runtime.InteropServices.FieldOffset(14) public byte b;第76页,共244页。Condition属性 (特性)当调用标记为条件的方法时,指定的预处理符号的存在或不存在决定是否包含或省略此调用。如果定义了该符号,则包含调用;否则省略调用。使用 Conditional 是封闭 #if 和 #endif 内部方法的替代方法,它更整洁、更别致、减少了出错的机会,如下例所示: Conditional(DEB

49、UG)static void DebugMethod()等同如下:#if DEBUGvoid ConditionalMethod()#endif第77页,共244页。全局属性 (特性)assembly: AssemblyTitle(WindowsApplication1)assembly: AssemblyDescription()assembly: AssemblyConfiguration()assembly: AssemblyCompany(Microsoft)assembly: AssemblyProduct(WindowsApplication1)assembly: Assembly

50、Copyright(Copyright Microsoft 2005)assembly: AssemblyTrademark()assembly: AssemblyCulture()第78页,共244页。属性 (特性)示例SampleCSharpAttributeAttributes第79页,共244页。属性 (特性)BrowsableAttribute:标记属性在PropertyGrid中是否可见。Browsable(true)public int MyProperty get return 0;第80页,共244页。属性 (特性)CategoryAttribute:在PropertyGri

51、d中的分类Category(Alignment”)public ContentAlignment TextAlignment getset第81页,共244页。属性 (特性)DescriptionAttribute:在PropertyGrid中的属性说明Description(背景颜色) public Color BorderColorget set 第82页,共244页。属性 (特性)DefaultValueAttribute:默认值private bool myVal=false;DefaultValue(false)public bool MyProperty get return my

52、Val;set myVal=value;第83页,共244页。属性 (特性)练习定义一个类把特性BrowsableAttribute、 CategoryAttribute、 DescriptionAttribute加到属性中,在PropertyGrid中观察结果。第84页,共244页。thisthis 关键字引用类的当前实例,还可用作扩展方法的第一个参数的修饰符。第85页,共244页。方法方法的定义attributes modifier return-type mothd-name(parameter-list)modifier:public、proteced、private、static、v

53、irtual、override、sealed、abstract、externclass testpublic int Max(int x, int y)if(x y) return x;else return y;第86页,共244页。方法的参数值参数引用型参数输出型参数可变参数第87页,共244页。值参数传递参数时方法不会修改实参值第88页,共244页。引用型参数传递参数时,传递实参的内存地址,方法可以改变参数的值class Teststatic void Swap(ref int x, ref int y)int temp = x;x = y;y = temp;static void Ma

54、in()int i = 2, j = 3;Swap(ref i, ref j);Console.WriteLine(i = 0, j = 1, i, j);输出结果:i = 3, j = 2第89页,共244页。向方法传递结构和向方法传递类引用之间的区别 class TheClass public string willIChange;struct TheStruct public string willIChange;class TestClassAndStruct static void ClassTaker(TheClass c) c.willIChange = Changed; sta

55、tic void StructTaker(TheStruct s) s.willIChange = Changed; static void Main() TheClass testClass = new TheClass(); TheStruct testStruct = new TheStruct(); testClass.willIChange = Not Changed; testStruct.willIChange = Not Changed; ClassTaker(testClass); StructTaker(testStruct); System.Console.WriteLi

56、ne(Class field = 0, testClass.willIChange); System.Console.WriteLine(Struct field = 0, testStruct.willIChange); Class field = ChangedStruct field = Not Changed第90页,共244页。输出型参数与引用型参数类似,只是不用对变量初始化class Teststatic void SplitPath(string path, out string dir, out string name)int i = path.Length;while(i 0

57、)char ch = pathi - 1;if(ch = | ch = / | ch = :) break;i-;dir = path.Substring(0, i);name = path.Substring(i);static void Main()string dir, name;SplitPath(c:windowsSystemhello.txt, out dir, out name);Console.WriteLine(dir);Console.WriteLine(name);第91页,共244页。可变参数可变参数必须是最后一个参数,并不能有ref、out修饰符。第92页,共244页

58、。方法的重载class Studentpublic int Max(int x, int y)if(x y) return x;return y;public float Max(float x, float y)if(x y) return x;return y;static void Main()int i = 2;int j = 3;Int k = Max(i, j);第93页,共244页。构造方法构造方法用于创建类实例class Apublic A() class Bpublic B() static void Main() A a = new A();第94页,共244页。不调用构造

59、函数初始化对象(3.0) 可以使用对象初始值设定项以声明性方式初始化类型对象,而无需调用类型的构造函数。 private class Cat / Auto-implemented properties public int Age get; set; public string Name get; set; static void MethodA() / Object initializer Cat cat = new Cat Age = 10, Name = Sylvester ;第95页,共244页。构造方法重载using System;class Point public int x,

60、y; / 缺省构造函数 public Point() x = 0; y = 0; / 有两个参数的构造函数 public Point(int x, int y) this.x = x; this.y = y; / 重载ToString函数 public override string ToString() return(String.Format(0,1), x, y); class MainClass static void Main() Point p1 = new Point(); Point p2 = new Point(5,3); / 用重载的ToString函数输出 Console

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论