《c#源代码》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
【实例2-1】usingSystem;usingSystem.Windows.Forms;namespaceTestEnum(publicpartialclassTestEnum:Form(//VisualStudio.Net自动生成的构造函数,后文示例将全部省略publicTestEnum()(InitializeComponent();}enumMyEnum{a=101,b,c,d=201,e,f};〃声明枚举型privatevoidTestEnumLoad(objectsender,EventArgse)(MyEnumx=MyEnum.f;〃使用枚举型MyEnumy=(MyEnum)202;stringresult="枚举数x的值为";result+=(int)x;〃将x转换为整数result+="
1枚举数y代表枚举元素”+y;IblShow.Text=result;)})【实例2-2】usingSystem;usingSystem.Windows.Forms;namespaceTestStru(publicpartialclassTestStru:Form(structStudent〃声明结构型(〃声明结构型的数据成员publicintno;pubIicstringname;pub1iccharsex;publicintscore;〃声明结构型的方法成员publicstringAnswer()stringresult=“该学生的信息如下:
2result+="
3学号:"+noJ〃"ヽn"为换行符result+="
4姓名:“+name;result+="
5性别:*+sex;result+="
6成绩:"+score;returnresult;〃返回结果)};privatevoidTestEnumLoad(objectsender,EventArgse)(Students;〃使用结构型5.no=101;s.name="黄海";5.sex二‘男‘;6.score=540;IblShow.Text=s.Answer0;〃显示该生信息IblShow.Text+="
7
8*+DateTime.Now;〃显示当前时间}}【实例2-3】usingSystem;classTestConstant(staticvoidMain(string[]args)〃有符号的32位整型常量〃无符号的32位整型常量〃64位的长整型常量〃32位的浮点型常量//64位的双精度型常量〃128位的小数型常量〃16位的字符型常量〃字符串常量〃64位的双精度型常量〃布尔型常量〃16位的字符型常量(Console.WriteLine((0).GetType());Console.WriteLine((OU).GetType());Console.WriteLine((0L).GetType());Console.WriteLine((OF).GetType());Console.WriteLine((0D).GetType());Console.WriteLine((0M).GetType());Console.WriteLine(('0').GetType());Console.WriteLine((*0*).GetType());Console.WriteLine((0.0).GetType());Console.WriteLine((true).GetType());Console.WriteLine(('\u004T).GetType());}【实例2-4】usingSystem;classTestVariable
9staticvoidMain(string[]args)inta=12,b=15,c,d,e;c=a+b;d=a-b;e=a*b;Console.WriteLine(*c={0}\td={l}\te={2}*,c,d,e);})【实例2-5]usingSystem;usingSystem.Windows.Forms;namespaceTestVariable{publicpartialclassTestOperator;Form(privatevoidTestVariableLoad(objectsender,EventArgse)(inti=5,j=5,p,q;P=(i++)+(i++)+(i++);q=(++j)+(++j)+(++j);stringt=;1blShow.Text=i+t+j+t+p+t+q;【实例2-6】usingSystem;usingSystem.Windows.Forms;namespaceTestVariable(publicpartialclassTestOperator:Form(privatevoidTestVariable_Load(objectsender,EventArgse)(inta,b=5;charcl='A';a=cl;〃字符型转整型floatx=3;x+=b;〃整型转浮点型1blShow.Text=*a=*+a;//整型转为字符串1blShow.Text+="
10x="+x;〃浮点型转为字符串【实例2-7】usingSystem;
11usingSystem.Windows.Forms;namespaceTestVariable(publicpartialclassTestOperator:Form{privatevoidTestVariableLoad(objectsender,EventArgse)(inti=25,j=12;boolk;stringresult=*i!=j的值为"+(i!=j);result+="
12i!=j&&i>:j的值为"+(i!=j&&i>=j);result+=*
13i!=j&&i>=j+20的值为"+(i!=j&&i>=j+20);result+="
14k=i!=j&&i>=j的值为"+(i!=j&&i>=j);1blShow.rFext=result;}}【实例2・8】usingSystem;usingSystem.Windows.Forms;namespaceTestinterface(publicpartialclassTestInterface:Form(interfaceIStudent〃声明接口(stringAnswer();}classStudent:IStudent〃声明类,以实现接n(publicintno;publicstringname;publicstringAnswer()(stringresult="该学生信息如下:*;result+="
15学号:*+no;result+:.
16姓名:”+name;returnresult;privatevoidbtnOk_Click(objectsender,EventArgse)Studenta=newStudent();〃定义并初始化变量aa.no=Convert.ToInt32(txtStuID.Text);a.name=txtName.Text;
17IblShow.Text=a.Answer();}))【实例2-9]usingSystem;classHeiloWorld(publicstringHeiloCN()(return"你好!我是罗福强,中国人。”;}publicstringHeiloEN()(return'Hi!IamJackson,aAmerican.}}classTestDelegate{delegatestringMyDelegateO;〃声明委托staticvoidMain(string[]args)(HeiloWor1dhello=newHe11oWor1d();〃创建对象li=newMyDelegati(helHelloCN);〃创建委托对象并指向,个方法Console.WriteLine(h());〃通过委托对象调用所指向的方法h=newMyDelegate(hello.HelloEN);Console.WriteLine(h());)【实例2-10]usingSystem;classTestArray(staticvoidMain(string[]args){int[]x,y;〃声明数组x=newint[5]{1,5,3,2,4);〃初始化数组y=newint[5];Array.Copy(x,y,5);〃将数组x的5个元素复制到数组y中Console.WriteLine("成功地从数组x复制到数组y,数组y各元素值如下:");for(inti=0;i 18经过排序后,数组x各元素值如下:");for(inti=0;i 19)}【实例2-11】usingSystem;usingSystem.Windows.Forms;usingSystem.Text;namespaceTestString(publicpartialclassTestString:Form(privatevoidTestStringLoad(objectsender,EventArgse)(strings;〃定义字符串变量StringBuiIdersb=newStringBuilder():〃创建可变字符串对象sb.Append("北运");〃添加字符串sb.Insert(1,"京奥”);〃插入字符串s=sb.ToStringO;〃把可变字符串对象转化为字符串s=s.Insert(s.Length,"2008");IblShow.Text="\""+s+"ヽ"长度为"+s.Length;))【实例2・12】usingSystem;usingSystem.Windows.Forms;namespaceTestIf(publicpartialclassTestinterface:Form(privatevoidbtnOk_Click(objectsender,EventArgse)charc=Convert.ToChar(txtChar.Text);〃字符串转换为字符型if(Char.IsLetter(c))if(Char.Islower(c))(IblShow.Text="这是ー个小写字母。”;}elseif(Char.Islipper(c))(IblShow.Text=”这是大写字母。”;}else(IblShow.Textゴ这是中文字符。";)}else(IblShow.Text=”这不是语言文字。)}) 20【实例2-13]usingSystem;classTestSwitch(staticvoidMain()(Console.WriteLine("服装类别:1二休闲装2二西装3二皮衣”);Console.Write("请选择类别:");strings=Console.ReadLine();intn=Convert.Tolnt16(s);〃把数字形式的字符串转化为整型数intt,cost=0;〃t用来记录数量,cost用来记录金额switch(n)(case1:Console.Write("休闲装的套数:");s=Console.ReadLine();t=Convert.Tolnt16(s);cost=t*150;break;case2:Console.Write("西装的套数:");s=Console.ReadLine();t=Convert.Tolnt16(s);cost=t*300;break;case3:Console.Write("皮衣的件数:");s=Console.ReadLineO;t=Convert.Tolnt16(s);cost=t*600;break;default:Console.WriteLine("无效选择,请输入1、2或3!");break;}if(cost!=0)(Console.WriteLine("应付款{〇}元.",cost);}Console.WriteLine("谢谢您的惠顾!");})【实例2-14】usingSystem; 21usingSystem.Windows.Forms;namespaceTestWhile(publicpartialclassTestWhi1e:Form(publicTestWhileO//VisualStudio.Net自动生成的构造函数(InitializeComponent();}privatevoidTestWhile_Load(objectsender,EventArgse)(inti,sum;i=l:〃循环变量赋初值sum=0;while(i<=100)〃循环条件{//循环体sum=sum+i;i++;〃改变循环变量的值MessageBox.Show("l到100的自然数之和="+sum);〃显示计算结果【实例2-15]usingSystem;classTestDoWhile(staticvoidMainO(charc;intn=0;Console.WriteLine("请输入一行字符:“);do(c=(char)Console.Read();if(c>='A'&&c<=||c>='a'&&cく='z')(n++;}}while(c!=> 22*);Console.WriteLine("该行中英文字母的个数为:{0}",n);}1【实例2・16】usingSystem;usingSystem.Windows.Forms;namespaceTestFor(publicpartialclassTestFor:Form 23{publicTestForO(InitializeComponent();}privatevoidTestWhileLoad(objectsender,EventArgse)(inti;intt;longsi,s2;si=t=1;/・百万富翁第一天给陌生人的钱为1分・/s2=100000;/・陌生人第一天给百万富翁的钱为十万元・/for(i=2;i<=30;i++)(t=t*2;/・百万富翁第i天给陌生人的钱・/si=si+t;/・百万富翁第i天后共给陌生人的钱・/s2=s2+100000;/・陌生人第i天后共百万富翁的钱・/si=si/100;/・将百分富翁给陌生人的分币换成元・/MessageBox.Show("百万富翁给陌生人"+sl+"元。'n陌生人给百万富翁"+s2+"元。");}【实例2-17]usingSystem;classTestForeach(staticvoidMainO(string[]names=newstring[5];Console.WriteLine("请输入五个人的姓名:“);for(inti=0;i 24Console.Write(*");}for(k=0;k<2*i+1;k++)〃k表示在第i行的第k个星号字符,Console.Write("*");Console.Write(* 25*);【实例2・21】usingSystem;classTestGoto(staticvoidMainO(charc;for(inti二〇;iく80;i++)〃最多输入80个字符(c=(char)Console.ReadO;if(c==)break;〃一旦输入星号就结朿Console.Write(c);}})【实例2-22]usingSystem;classTestContinue(staticvoidMainO(charch_old,ch_new;ch_old=’.';Console.WriteLine("请输入一串字符,以句号结尾:");do(ch_new=(char)Console.ReadO;if(ch_new==ch_old)continue;Console.Write(chnew);ch_old=ch_new;}while(ch_new!=*.');Console.Write(* 26*); 27))【实例3-1】usingSystem;publicclassPerson〃定义类的数据成员pub1icstringName;publicintAge;〃定义类的方法成员publicstringAnswer()(returnstring.Format("姓名:{0}»年龄:{1}岁。",Name,Age);classTestClass(staticvoidMainO(Personp=newPerson();〃声明并创建对象p.Name="黄飞鸿";〃修改对象的数据成员的值p.Age=25;Strings=p.Answer();〃调用对象的方法成员Console.WriteLine(s);}【实例3-2]usingSystem;classCircle(〃定义私有常量和字段privateconstfloatpi=3.14F,xO=0,yO=0;privatefloatr;privatefloatx,y;〃定义属性RpublicfloatR(get(returnr;}set 28(if(value<0)r=0;elsevalue;〃定义只读属性LpublicfloatL{get(return2*pi*r;classTestClassMember{staticvoidMainO(Circlec=newCircle0;Console.Write("圆半径:");c.R=Convert.ToSingle(Console.ReadLineO);/,数据ムと终保存在.字段「屮float1=c.L;Console.WriteLine(“圆的周长为:{0}",1);})【实例3-3]usingSystem;classCircle(〃定义私有常量和字段privateconstf1oatpi=3.14F,x0=0,y0=0;privatefloatr;〃定义属性RpublicfloatR(get(returnr;)set( 29if(value<0)r=0;elser=value;}}〃使用嵌套类来计算圆面上的点到圆心的距离publicdoubIePointDistance(floatx,floaty)if(x>RI,y>R)return0;Pointp=newPoint(x,y)1〃嵌套类实例化returnp.Distance0J〃调用嵌套类的方法成员}〃嵌套类,默认为private,只能被包含类Circle使用classPoint{privatefloatX;privatefloatY;〃构造函数publicPoint(floatx,floaty)(X=x;Y=y;}〃计算圆面上的点到圆心的距离publicdoubleDistanceO(returnMath.Sqrt(X*X+Y*Y);//在TeslClassMember类不能使用包含Circle中的嵌套类PoinlclassTestClassMember(staticvoidMainO{Circlec=newCircle();Console.Write("圆半径:");c.R=Convert.ToSingle(Console.ReadLine());Console.WriteLine("请输入圆面上的点的坐标:");floatx=Convert.ToSingle(Console.ReadLine());floaty=Convert.ToSingle(Console.ReadLine());floatd=(float)c.PointDistance(x,y); 30if(d!=0&&d<=c.R)Console.WriteLine("该点离圆心的距离为:{0}",d);elseConsole.WriteLine("该点不是圆面上的点。"); 31【实例3-4】usingSystem;classSwaper(publicvoidSwap(intx,inty)〃被调用方,其中x和y是整型形参{inttemp;temp=x;x=y;y=temp;Console.WriteLine("交换之后:{0},{1}\x,y);)}classTestMethod(staticvoidMainO〃调用方,其中a和b是整型实参(Swapers=newSwaper():〃创建对象Console.WriteLine("请任意输入两个整型数:つ;inta=Convert,Tolnt32(Console.ReadLineO);intb=Convert.Tolnt32(Console.ReadLineO);5.Swap(a,b):〃调用并传递参数Console.WriteLine("交换之前:{0},{1}*,a,b);)}【实例3-5】usingSystem;classSwaper(publicvoidSwap(refintx,refinty)〃被调用方,其中x和y是引用型形参{Console.WriteLine("形参的值未交换:{0},{1}”,x,y);inttemp;temp=x;x=y;y=temp;Console.WriteLine("形参的值已交换:{0},{1}”,x,y);)}classTestMethodstaticvoidMainO//调用方,其中实参是a和b的引用Swapers=newSwaper()I〃创建对象Console.WriteLine("请任意输入两个整型数:");inta=Convert.Tolnt32(Console.ReadLineO);intb=Convert.Tolnt32(Console.ReadLineO);s.Swap(refa,refb)J〃调用并传递参数Console.WriteLine("实参的值已交换:{0},{1}”,a,b);)【实例3・6】usingSystem;classAnalyzer(〃从文件路径中分离路径和文件名,定义了两个输出参数publicvoidSplitPath(stringpath,outstringdir,outstringfilename)(inti; 32〃寻找路径和文件名之间的间隔符、或:所在位置for(i=path.Length;i>=0;i—)(charc=path[i一1];if(c==>WI丨c='ゴ)break;)//提取路径和文件名dir=path.Substring(0,i-l);fi1ename=path.Substring(i);)}classTestMethod(staticvoidMainO〃调用方,其中实参dir和file是输出参数(Analyzera=newAnalyzer();〃创建对象Console.WriteLine("请ー个文件的路径:つ;stringpath=Console.ReadLineO;stringdir,file;a.SplitPath(path,outdir,outfile);〃调用方法Console.WriteLine("文件所位目录:{〇} 33文件名:{1}”,dir,file);)【实例3-7】usingSystem;classMaxer〃求最大数,形参为普通数组,实参必须为数组publicintMaxi(int[]numbers){intk=0;〃求最大数的索引for(inti=0;i 34)returnnumbers[k];classTestMethod(staticvoidMain()(Maxerm=newMaxer()J〃创建对象int[]a=newint[]{4,7,1,3,2,8,6,5};intmax=m.Max1(a);〃调用方法,实参为己初始化的数组Console.WriteLine("使用第一种方法得最大数为:{0}",max);max=m.Max2(4,7,1,3,2,8,6,5);//调用方法,实参为数据列表Console.WriteLine("使用第二种方法得最大数为:{0)",max);}【实例3・8】usingSystem;classMaxer 35〃求最大整数publicintMax(paramsint[]datas){intk=0;〃求最大数的索引for(inti=0;i 36intimax=m.Max(4,7,1,3,2,8,6,5);Console.WriteLine("最大的整数为:{0)",imax);doublefmax=m.Max(4.5,7.8,1.3,2.9,8.4,5.5);Console.WriteLine("最大的浮点数为:{〇}",fmax);stringsmax=m.Max(Are,you,going,to,Scarborough,Fair);Console.WriteLine("最长的字符串为:{0}",smax);))【实例3-9】usingSystem;classPark(〃定义字段成员,其中有两个只读字段publicreadonlystringname;publicreadonlystringaddress;publicdecimalprice;〃重载构造函数,以初始化字段成员publicPark(stringname,stringaddress,decimalprice)(this,name=name;this,address=address;this,price=price;}}classTestConstructor(staticvoidMain(){Parkp二newPark("成都胜利公园","成都市蜀都大道100号”,20);Console.WriteLine("{0}»地址:{1}»门票价格:{2}元。",p.name,p.address,p.price);p.ncime="成都新华公园”;/・错误,不能修改只读字段的值//p.price=5;Console.WriteLine("{0}»地址:{1},门票最新价格:{2}元。",p.name,p.address,p.price);})【实例3-10]usingSystem;classPark(publicreadonlystringname;publicreadonlystringaddress;publicdecimalprice;〃声明构造函数pub1icPark(stringname,stringaddress,decimalprice)this,name=name;this,address=address;this,price=price;Console.WriteLine("构造函数已被执行,对象已创建成功!”);)〃声明析构函数 37~Park()(Console.WriteLine("析构函数已被执行,该对象即将被销毁!”);)}classTestDestructor(staticvoidMainO{〃调用构造函数来创建对象Parkp=newPark("成都胜利公园","成都市蜀都大道100号",20);Console.WriteLine("该对象的数据有:{0},{1),(2)〇",p.name,p.address,p.price);}【实例3-11]usingSystem;〃声明表示性别的枚举型publicenumGender{男,女};publicclassPerson{〃私有静态字段,分别统计男女人数privatestaticintmales;privatestaticintfemales;〃公共字段,描述个人信息pub1icstringName;publicGenderSex;publicintAge;〃构造函数,用来初始化对象publicPerson(stringname,Gendersex,intage)(Name=name;Sex=sex;Age=age;if(sex==Gender.男)males++;if(sex==Gender.女)females++;〃返回男生人数publicstaticintNumberMales()(returnmales;)〃返回女生人数 38publicstaticintNumberFemales0(returnfemales;)}classTestClass(staticvoidMainO{〃创建Person型的数组对象,用来记录5个人的信息Person[]ps=newPerson[5];ps[0]=newPerson("张伟",Gender.男,20);ps[l]=newPerson("李静",Gender.女,21);ps[2]=newPerson("黄薇",Gender.女,19);ps[3]=newPerson("赵恒",Gender.男,22);ps[4]=newPerson("钱沿",Gender.男,20);Console.WriteLine("男生人数:{0}",Person.NumberMalesO);Console.WriteLine("女生人数:{0}",Person.NumberFemales());Console.WriteLine("学生名单如下:");foreach(Personpinps)(Console.Write("{0}\t",p.Name);)Console.WriteC 39');【实例3-12]usingSystem;classTest(publicintx;〃声明非静态字段staticpublicinty;〃声明静态字段/〃字段初始化publicvoidSetValue(intx,inty)this,x=x;Test,y=yi〃不能使用this来引用静态字段y})classTestStatic(staticvoidMainO 40(〃创建对象,并初始化字段Testt=newTest();s.SetValue(l,1);Console.WriteLine(*{0},{l)*,t.x,Test,y);〃修改字段的值t.x++;Test.y++;〃不能通过对象来操作字段yConsole.WriteLine(*{0},{1}*,t.x,Test,y);〃重新创建对象t=newTest();Console.WriteLine(*{0},(1)*,t.x,Test,y);)}【实例3-13】usingSystem;classTest(publicintx;staticpublicinty;〃实例构造函数,初始化字段xpub1icTest(intx)(this,x=x;)〃静态构造函数,初始化静态字段ystaticTest()(y=1;)}classTestStatic(staticvoidMainO〃调用实例构造函数创建对象,静态构造函数将自动被调用Testt=newTest(1);〃字段x和y都将被初始化Console.WriteLineC{0},{1)*,t.x,Test,y);〃修改字段的值t.x++;Test.y++;Console.WriteLine(*{0},{1}*,t.x,Test,y);〃调用实例构造函数重新创建对象,但静态构造函数不会被调用t=newTest(0)I〃只有字段x被初始化Console.WriteLine(*{01,(1)*,t.x,Test,y);}【实例41】usingSystem;publicclassPerson〃这是ー个基类 41(〃定义数据成员publicstringName:〃姓名publiccharSex;〃性别〃定义构造函数,以初始化字段pub1icPerson(stringname,charsex)(Name=name;Sex=sex;}〃定义方法成员pub1icstringAnswer()(returnstring.Format("姓名:{0}»性别:{1J〇",Name,Sex);}}publicclassStudent:Person〃这是•个派生类(〃扩展数据成员publicstringSchool;〃学校privateintScore;〃成绩〃定义构造函数,自动调用基类的构造函数辅助完成字段的初始化publicStudent(stringname,charsex,stringschool,intscore):base(name,sex){School=school;Score=score;}〃扩展方法成员pub1icfloatExamineO〃返回考试成绩returnScore;})classTestClass(staticvoidMainO(〃创建Student对象Students=newStudent("张伟",,男’,“电子科大成都学院”,480);Console.WriteLine("该生信息如ド:つ;Console.WriteLine(s.Answer());〃调用对象・继承来的方法Console.WriteLine("学校:(0)»考试成绩:{1}”,s.School,s.Examine0); 42}【实例4-2】usingSystem;publicclassPerson〃这是个基类(〃定义数据成员publicstringName;〃姓名publiccharSex;〃性别〃定义构造函数,以初始化字段publicPerson(stringname,charsex)(Name=name;Sex=sex;}〃声明虚拟方法成员publicvirtualstringAnswer()(returnstring.Format("姓名:{0}»性别:{1I0",Name,Sex);publicclassStudent:Person〃这是ー个派生类(〃扩展数据成员publicstringSchool;〃学校publicintScore;〃成绩〃定义构造函数,自动调用基类的构造函数辅助完成字段的初始化publicStudent(stringname,charsex,stringschool,intscore):base(name,sex)School=school;Score=score;〃覆盖基类的方法成员publicoverridestringAnswer(){returnstring.Format("姓名:{0}»性别:{l} 43学校:{2},成绩:{3}分。Name,Sex,School,Score);}}publicclassWorker:Person〃这是ー个派生类(〃扩展数据成员publicstringDepartmentI〃部IJ 44publicfloatSalary:〃薪水〃定义构造函数,自动调用基类的构造函数辅助完成字段的初始化publicWorker(stringname,charsex,stringdepart,floatsalary):base(name,sex){Department=depart;Salary=salary;}〃覆盖基类的方法成员publicoverridestringAnswer()(returnstring.Format("姓名:{〇},性别:{l} 45部门:{2},薪水:{3}元。Name,Sex,Department,Salary);}}classTestClass(staticvoidMain()(〃创建学生对象Students=newStudent("张伟",’男‘,"电子科大成都学院",480);Console.WriteLine("该学生信息如ド:");Console.WriteLine(s.Answer());〃创建员エ对象Workerw=newWorker("王刚",’男',"生产车间”,1500);Console.WriteLine("该员エ信息如下:");Console.WriteLine(w.Answer());【实例4-3】usingSystem;publicabstractclassShape//表示“形状”的抽象类型(privatestringm_id:〃定义形状的ID,ー个私有字段〃声明构造函数,用来设置属性IdpublicShape(strings){Id=s;}publicstringId〃定义属性,用来操作私有字段id(get(returnmid;}set(m_id=value; 46})/Z定义一个只读的抽象属性-表示形状的面积publicabstractdoubleArea(get;)〃重载从Ojbect类继承来的方法publicoverridestring'ToString0{returnId+・面积="+string.Format("{0:F2}",Area);}}publicclassSquare:Shape〃正方形,从抽象类Shape派生(privateintm_side;〃正方形的边长〃声明构造函数,联合基类的构造函数对字段成员进行初始化publicSquare(intside,stringid):base(id){mside=side;}〃重载继承来的抽象属性,得正方形的面积publicoverridedoubleArea 47returnmside*mside;})}classTestClass(staticvoidMainO(〃创建一个边长为5的正方形对象Squares=newSquare(5,“正方形”);stringresult=s.ToStringO;Console.WriteLine(result);}【实例4-4】usingSystem;interfaceIStudent(〃声明属性成员stringStudentID{get;set;}stringName{get;set;)charSex{get;set;}〃声明方法成员newstringAnswer();)interfaceISchool(〃声明属性成员stringSchoolName{get;set;}stringAddress{get;set;}〃声明方法成员stringAnswer();}publicclassStudent:IStudent,ISchool〃这ー个从多个接口继承的派生类(〃定义私有字段privatestringStudentID;〃学号privatestringname;〃姓名privatecharsex;〃性别privatestringschoolName;//学校privatestringaddress;〃校址^regionIStudent成员〃实现IStudent接11所定义的属性publicstringStudentIDreturnstudentID;} 48set{studentID=value;}}publicstringName(get(returnname;}set(name=value;))publiccharSex{get(returnsex;)set(sex=value;})〃显示实现接口的方法stringIStudent.Answer0{strings="学号:—StudentID;s+="姓名:"+Name;s+="性别:"+Sex.ToStringO;returns;} 49Sendregion^regionISchool成员〃实现【School接H所定义的属性publicstringSchoolNamereturnschoolName;}set{schoolName=value;}}publicstringAddress(get(returnaddress;)set(address=value;}}//显示实现接口所定义的方法stringISchool.Answer()(strings=" 50学校:"+SchoolName;s+=・校址:"+Address;returns;)Sendregion〃构造函数,学校和校址可空白publicStudent(stringid,stringname,charsex)(StudentID=id;Name=name;Sex=sex;SchoolName=Address=**;)//构造函数,学校和校址不能空白publicStudent(stringid,stringname,charsex,stringschool,stringaddress)(StudentID=id;Name=name;Sex=sex; 51SchoolName=school;Address=address;}?classTestClass(staticvoidMain(){〃创建学生数组对象Student[]s=newStudent[2]:〃设置第一个学生的信息s[0]=newStudent(*2008100135","张三丰",‘男’);stringresult=((1Student)s[0]).Answer():〃先强制类型转换,再调用方法Console.WriteLine("学生甲: 52{0}*,result);〃设置第二个学生的信息s[l]=newStudent(*20008050301*,"黄倩影",‘女’,“电子科大成都学院","成都高新西区百叶路”);result=((IStudent)s[l]).Answer():〃强制类型转换,再调用方法result+=((ISchool)s[l]).Answer();・躯制类型转换,再调用方法Console.WriteLine("学生乙: 53{〇}",result);【实例4-5】//files.csusingSystem;〃引用.NetFramework类库namespaceLfq.Sales〃声明自定义的命名空间(publicclassCustomer〃声明顾客类(publicvoidAnswer()(Console.WriteLine("我是一个顾客!”);//file2.csusingLfq.Sales;〃引用已定义的命名空间namespaceLfq.Designs〃声明自定义的命名空间(publicclassDesigner〃声明设计师类(staticvoidMain()(〃创建对象,调用其方法成员Customerc=newCustomerQ;c.Answer();) 54【实例4-61usingSystem;public加legaleintCaculate(intx,inty);〃声明委托publicclassCaculateOfNumber〃声明类(publicCaculatehandler;//这是ー个委托型的字段publicintProduct(intx,inty)(returnx*y;}publicintAverage(intx,inty){return(x+y)/2;publicclassTestDelegate(staticvoidMainO(inta=5,b=6;CaculateOfNumbercn=newCaculateOfNumber();〃创建一个对象cn.handler=newCaculate(cn.Product);〃初始化委托型字段//通过委托来调用方法Console.WriteLine("{0}与{1}的乘积为{2}",a,b,cn.handler(a,b));cn.handler=newCaculate(cn.Average);Console.WriteLine("{0}与{1}的平均值为{2}”,a,b,cn.handler(a,b));〃使用匿名方法来初始化委托型字段cn.handler=delegate(intx,inty){return(int)Math.Pow(x,y););Console.WriteLine("{0}的{1}次方值为{2}",a,b,cn.handler(a,b));})【实例4-7】usingSystem;publicdelegatePersonPointPerson(inti);〃声明委托,返回第i个人员publicdelegateintPosition(Students);〃声明委托,返回指定学生的位置publicclassPerson〃这是ー个基类 55pubIicstringname;publiccharsex;〃构造函数publicPerson(stringname,charsex)(this,name=name;this.sex=sex;})publicclassStudent:Person4是,个派(publicstringschool;〃构造函数publicStudent(stringname,charsex,stringschool):base(name,sex)(this,school=school;}}publicclassPersons〃若干个人员的集合(privatePerson[]p=newPerson[5];publicPersonthis[inti]〃声明索引器if(i<0Ii>=p.Length)p[0]=value;elsep[i]=value;})publicPersongetPerson(inti)〃返冋第i个人(if(i<0IIi>=p.Length)returnp[0];elsereturnp[i];)publicintgetPos(Personper)〃返冋某个人的位置(intk=-1;〃如果此人不存在,返回一1for(inti=0;i 56returnk;publicclassStudents〃若干个学生的集合{privateStudent[]p=newStudent[5];publicStudentthis[inti]〃声明索引器if(i<0IIi>=p.Length)p[0]=value;elsep[i]=value;)}publicStudentgetStudent(inti)〃返回第i个学生{if(i<0IIi>=p.Length)returnp[0];elsereturnp[i];}publicintgetPos(Studentper)〃返回指定学生的位置{intk=-1:〃如果该生不存在,返冋Tfor(inti=0;i 57s[3]:newStudent("赵霞",‘女',"电子科大成都学院");s[4]=newStudent("梅岭",‘男’,"成都东软学院”);〃创建返回值为Person型的委托对象并指定引用Students集合的getStudent方法PointPersonpoint=newPointPerson(s.getStudent);for(inti=0;i<5;i++)(Persona=point(i);〃协变委托方法调用Console.WriteLine("姓名:{〇}\t性别:(1)〇”,a.name,a.sex);)〃创建人员集合并存入5个人的信息Personsp=newPersons();p[0]=newPerson("许珊珊",'女');p[l]=newPerson("尹佳云",'女');p⑵=newPerson("周巍",'男');p[3]=newPerson("杨森",'男');p[4]=newPerson("刘通",'男');〃创建参数为Studenl的委托对象,并指定引用Perons集合的getPosPositionpos=newPosition(p.getPos);intk=pos(newStudent("周巍",‘男’,“电子科大成都学院"));〃逆变委托方法调用Console.WriteLine("该生是第{〇}个学生。",k+1);}I.【实例4-8】usingSystem;publicdelegatevoidCaculate(intx,inty);〃声明委托publicclassCaculateOfNumber〃声明类(publicCaculatehandler;〃这是ー个委托型的字段publicvoidProduct(intx,inty){Console.WriteLine("{0}与{1}的乘积为{2}”,x,y,x*y);}pubIicvoidAverage(intx,inty)(Console.WriteLine("{〇}与⑴的平均值为⑵",x,y,(x+y)/2);)publicvoidPow(intx,inty)Console.WriteLine("{0}的{1}次方值为{2}",x,y,(int)Math.Pow(x,y));publicclassTestDelegatestaticvoidMainO 58{inta=5,b=6;CaculateOfNumbercn=newCaculateOfNumber()J〃创建一个对象〃使用多路广播机制来创建委托调用列表cn.handler=newCaculate(cn.Product);cn.handler+=newCaculate(cn.Average);cn.handler+=newCaculate(cn.Pow);〃・次性调用上面指定的方法cn.handler(a,b);}}【实例5-1】usingSystem;usingSystem.Collections;classStudent(publicstringName;publiccharSex;publicStudent(stringname,charsex)〃构造函数(Name=name;Sex=sex;)publicstringAnswer()(return"姓名:"+Name+*性别:"+Sex;)}publicclassTestHash(staticvoidMainO(Hashtableh=newHashtableO;〃创建哈希表对象Studentp=newStudent("黄鸿",‘男’);h.Add("甲",p);〃将键值对存入哈希表‘键为"甲",值为学生对象p=newStudent("何娟",‘女’);h.Add("乙",p);p=newStudent("王川",'男');h.Add("丙",p); 591Collectionc=h.Values;〃返回哈希表所有键/值对的值IEnumeratorie=c.GetEnumerator():〃把哈希表的值集合转换为枚举器while(ie.MoveNext())〃遍历枚举器strings二((Student)ie.Current).Answer();Console.WriteLine(s);}【实例5-2】usingSystem;classZ〃这是ー个能容纳100个整数的集合privatelong[]arr=newlong[100];publiclongthis[intindex]〃声明一个私有数组成员//声明索引器getif(indexく0index>=100)returnarr[0];elsereturnarr[index];setif(index<0I|index>=100)arr[0]=value;elsearr[index]=value;publiclongPow(intx,inty)〃计算x的y次方return(long)Math.Pow(x,y);publicclassTestIndexerstaticvoidMain()Zz=newfor(intiZ0;=0;i<100;i++)〃创建整数集对象//计算1到100这100个数字的3次方z[i]=z.Pow(i+1,3);〃把计算结果通过索引器赋值给相应数组元素 60}Console.WriteLine("l到100间的整数的3次方值依次如下:");for(inti=0;i<100;i++)(Console.Write("{0}、z[i]);〃通过索引器逐个输岀数:元素的值})【实例5-3】usingSystem;publicinterfacelAddress(stringthis[intindex]{get;set;}〃声明索引器stringgetAddress0;〃声明方法)publicclassAddress:lAddress〃从接口派生(privatestring[]addr=newstring[5];pub1icstringthis[intindex!〃实现接口的索引器(get{if(index<0|index>=5)returnaddr[0];elsereturnaddr[index];}set(if(index<0||index>=5)addr[0]=value;elseaddr[index]=value;;}}publicstringgetAddress()〃实现接口的方法,返回地址信息(strings=addr[0]+"省”;s+=addr[l]+"市";s+=addr[2]+"街";s+=addr[3]+"号";s+=addr[4]+"单元";returns;}}publicclassStudentpublicstringName; 61pub1icAddressAddr=newAddress();publicStudent(paramsstring[]info)〃声明构造函数(Name=info[〇];for(inti二〇;i 62";s+="地址:"+Addr.getAddress();returns;publicclassTestIndexer(staticvoidMain()〃创建Student对象,保存并输出学生信息Studentstud:newStudent("余果","四川","成都","羊市","120","4-9-1");Console.WriteLine(stud.Answer());stud:newStudent("何苗","山西","大同","大禹","210","1-2-8");Console.WriteLine(stud.Answer());)【实例5-41usingSystem;publicclassPerson〃这是ー个基类〃字段成员pub1icstringName;publiccharSex;publicstringDepartment;〃构造函数publicPerson(stringname,〃姓名〃性别〃班级charsex,stringdepartment)Name=name;Sex=sex;Department=department;}publicclassStudent:Person〃这是•个派生类publicStudent(stringname,charsex,stringdepartment):base(name,sex,department) 63()〃返回学生信息publicstringgetlnfoO{stringresult="姓名:"+Name;result+="\t性别:"+Sex;result+="\t班级:"+Department;returnresult;}1publicclassTeacher:Person(publicTeacher(stringname,charsex,stringdepartment):base(ntime,sex,department)〃声明一个泛型类,能容纳5个人的信息publicclassPersons 64〃返回指定个人的信息publicstringgetlnfo(intindex)(stringresult="姓名:"+this[index].Name;result+="\t性别:"+this[index].Sex;result+="\t部门:*+this[index].Department;returnresult;})publicclassTestGeneric(staticvoidMainO(〃利用泛型类来创建学生集,实际类型参数为StudentPersonsくSludent>s=newPersons 65}publicStudentstudent〃只读属性(get{returnsomeone;}))classGrades〃班级类,也是事件的发送者(privateArraylJstlist;〃声明列表,用来保存本班已报到的学生信息〃声明新生报到的委托类型publicdelegatevoidStudentHandler(Objectsender,StudentEventArgse);publiceventStudentHandleronNewStudent;〃声明新生注册’ル件〃构造函数publicGrades()(1ist=newArrayList();}〃新生s在班级名单上登记报到publicvoidAdd(Students)1ist.Add(s);)〃注册到学校花名册,同时发布事件publicvoidProcessRegister0(Students;for(inti=0;i 66return(Student)1ist[0];elsereturn(Student)1ist[index];}}〃声明属性,返回全校学生人数publicintCount(get{returnstudents;}}〃声明事件函数,将学生s注册到学校花名册中privatevoidAdd_NewStudent(Objectsender,StudentEventArgse)if(e.student!=null)students++;〃学生人数增加1list.Add(e.student);〃把接收到的学生信息存入列表中}}〃声明一个订阅新生注册事件的方法publicvoidAddStudents(Gradesg)(〃绑定事件与事件处理程序g.onNewStudent+=newGrades.StudentHandler(this.AddNewStudent);publicclassTestEvent(staticvoidMainO(Gradesg=newGrades()i〃创建班级对象Schoolschool=newSchool():〃创建学校对象〃学生报到登记Students=newStudent("邹永",’男’);g.Add(s);s=newStudent("钟哲",’男’);g.Add(s);s=newSludent("许艳丽",'女');g.Add(s);school.AddStudents(g);〃订阅事件g.ProcessRegisterO;〃以班级为单位进行学生注册,注册时发布事件 67Console.WriteLine("全校已注册的学生共计{〇}人,详细名单如ド:",school.Count);for(inti=0;i 68IstSpec.Jterns.Clear();IstSpec.Items.Add("通信工程");IstSpec.Items.Add("电子信息工程");IstSpec.Items.Add("电磁场与无线技术");IstSpec.Items.Add("机械设计制造及其自动化");break;case"经济与管理工程系":IstSpec.Items.Clear();1stSpec.Items.Add("国际经济与贸易");IstSpec.Iterns.Add("电子商务");IstSpec.Items.Add("信息管理与信息系统"レIstSpec.Items.Add("财务管理");break;case"图形艺术系":IstSpec.Items.Clear。:IstSpec.Items.Add("数字动画");IstSpec.Items.Add("影视动画”);IstSpec.Items.Add("商用插画"); 69break;default:IstSpec.Items.Clear();IstSpec.Items.Add("暂无");break;}IstSpec.Selectedlndex=0;privatevoidbtnYes_Click(objectsender,EventArgse){stringsex=;if(rdoMale.Cheeked)sex=rdoMale.Text;elsesex=rdoFemale.*Fext;stringdept=cboDept.Selectedltem.ToStringO;stringspec=IstSpec.Selectedltem.ToStringO;stringhobb尸:if(checkBoxl.Checked)hobby+=checkBoxl.Text;if(checkBox2.Checked)hobby+:”、"+checkBox2.Text;if(checkBox3.Checked)hobby+二if(checkBox4.Checked)hobby+=if(checkBox5.Checked)hobby+=+checkBox3.Text;+checkBox4.Text;+checkBox5.Text;if(checkBox6.Checked)hobby+=+checkBox6.Text;stringstudentMessage="您的姓名是:"+txtName.Text+" 70性别为:"+sex+" 71您是"+dept+"系"+spec+"专业的学生'n您的兴趣是:"+hobby;MessageBox.Show(studentMessage,"学生,信息",MessageBoxBu11ons.OK,MessageBoxIcon.Information);privatevoidbtnCloseClick(objectsender,EventArgse)(this.Close0;)【实例7-3】publicpartialclassCourseMsgFrm:Form(stringcourseName;stringcourseClass;stringrequired;intcredit;intprelectionCredit;intExperimentcredit;publicCourseMsgFrm(){InitializeComponent();privatevoidbtnNext_Click(objectsender,EventArgse)〃如果课程名为空或课程类别未选择,则弹出对话框告知用户if(txtName.Text=丨丨cboClass.Selectedlndex<0I(rdoRequired.Checked=false&&rdoElective.Checked=false))( 72MessageBox.Show("输入信息不完整!","信息不完整”,MessagcBoxButtons.OK,MessageBoxIcon.Exclamation);)else(tabControll.SelectedTab=tabPage2;〃显示"确认信息”选项卡}}privatevoidtabControlISelectedlndexChanged(objectsender,EventArgse)(if(tabControll.Selectedlndex==1)(if(txtName.Text=""\cboClass.Selectedlndex<0I(rdoRequired.Checked==false&&rdoElective.Checked==false))(MessageBox.Show("输入信息不完整!","信息不完整",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);tabControll.SelectedTab=tabPage1;)else(courseName=txtName.Text;courseClass=cboClass.Selectedltem.ToStringO;required=rdoRequired.Checked?"必修":"选修";credit=(int)nudCredit.Value;prelectionCredit=(int)nudPrelection.Value;ExperimentCredit=(int)nudExp.Value;stringmessage=String.Format("课程名:{0}、n课程类别:{1} 73课程性质:{2} 74学分:{3} 75理论学时:{4} 76实验学时:{5}”,courseName,courseClass,required,credit,prelectionCredit,ExperimentCredit);richTextBoxl.Text=message;}))【实例7-4】privatevoidbtnYes_Click(objectsender,EventArgse)this.CloseO;关闭“关于”【实例7-6】publicpartialclassForm2:Form(publicstringmessage;publicForm2()(InitializeComponent();}privatevoidForm2Load(objectsender,EventArgse)(label1.Text=message;)privatevoidbutton1_C1ick(objectsender,EventArgse)(this.CloseO;} 77privatevoidbuttonl_Click(objectsender,EventArgse)(Form2frm=newForm2();〃新建•个窗体对象frm.message="这是ー个模态对话框!*;frm.ShowDialo晨);〃ShowDialog方法用于打开ー个模态对话框)【实例7-7】privatevoidbutton2Click(objectsender,EventArgse){Form2frm=newForm2();〃新建一ー个窗体対象frm.message="这是ー个非模态对话框!”;frm.Show。"/Show方法用「打开一个非模态対话框)【实例7-8】privatevoid字体FToolStripMenuItem_Click(objectsender,EventArgse)(fontDialogl.Font=richTextBoxl.Font;if(fontDialogl.ShowDialogO=DialogResult.OK)(richTextBoxl.Font=fontDialogl.Font;))privatevoid颜色CToolStripMenuItem_Click(objectsender,EventArgse)(colorDialogl.Color=richTextBoxl.ForeColor;if(colorDialogl.ShowDialogO==DialogResult.OK)richTextBoxl.ForeColor=colorDialogl.Color;【实例7-9】privatevoidtsmNewStudent_Click(objectsender,EventArgse)(StudentMsgFrmstudentMsgFrm=newStudentMsgFrmO;/Z创建子窗体对象studentMsgFrm.MdiParent=this;〃指定当前窗体为MDI父窗体studentMsgFrm.Show();〃打开「窗体tssMsg.Text=studentMsgFrm.Text;〃状态栏中显示操作内容}privatevoidtsmNewCourse_Click(objectsender,EventArgse)(CourseMsgFrmcourseMsgFrm=newCourseMsgFrmO;/Z创建:窗体对象courseMsgFrm.MdiParent=this;//指定当前窗体为MDI父窗体courseMsgFrm.Show();〃打开子窗体tssMsg.Text=courseMsgFrm.Text;//状态栏中显示操作内容}privatevoidtsmAboutClick(objectsender,EventArgse)(AboutFormaboutForm=newAboutFormO;/Z创建窗体对象aboutForm.ShowDialogO;〃打开窗体,该窗体是个模态窗体tssMsg.Text=aboutForm.Text;〃状态栏中显示操作内容}【实例8・1】privatevoidbtnAddClick(objectsender,EventArgse){StreamWritersw=newStreamWriter(@"d:\C#程序设计\abc.txt",true);sw.WriteLine(txtContent.Text);sw.CloseO;}privatevoidbtnShowClick(objectsender,EventArgse)(StreamReadersr=newStreamReader(/d:\C#程序设计\abc.txt");txtResult.Text=sr.ReadToEndO;;sr.CloseO;I. 78【实例8-2]privatevoidbtnAddClick(objectsender,EventArgse)(FileStreamfs=newFileStream(ザd:\C#程序设计、student.dat”,FileMode.Append,FileAccess.Write);BinaryWriterbw=newBinaryWriter(fs);bw.Write(txtNo.Text);bw.Write(txtName.Text);bw.Write(txtDepart.Text);fs.CloseO;bw.CloseO;)privatevoidbtnShow_Click(objectsender,EventArgse)(FiIeStreamfs=newFileStream(/d:\C#程序设计\student.dat”,FileMode.Open,FileAccess.Read);BinaryReaderbr=newBinaryReader(fs);fs.Position=0;while(fs.Position!=fs.Length)(strings_no=br.ReadStringO;stringname=br.ReadStringO;stringdepart=br.ReadStringO;stringresult=String.Format(*{0}\t{1}\t{2}*,s_no,name,depart);IbResult.Items.Add(result);}br.CloseO;fs.CloseO;)【实例8-3]usingSystem.Collections;[Serializable]classstudent〃学生类(publicstringstudent_no;publicstringname;publicstringdepartment;publicstudent(strings_no,stringname,stringdepart)〃构造函数(this.student_no=s_no;this,name=name;this,department=depart; 79}}[Serializable]publicclassStudentList〃学生列衣类{privateStudent[]list=newStudent[100];publicStudentthis[intindex]〃索引器getif(index<0I|index>=100)/Z检查索引范围.(returnlist[0];}else(returnlist[index];if(!(index<0||index>=100))(list[index]=value;}}}usingSystem.10;usingSystem.Runtime.Serialization.Formatters.Binary;publicpartialclassfrmDemo:Form{privateStudentListlist=newStudentList();〃声明一个学生列表privateinti=0;〃i用来标记即将加入列表中的学生,也代表学生的个数privatevoidbtnAdd_Click(objectsender,EventArgse)(Studentstudent=newStudent(txtNo.Text,txtName.Text,txtDepart.Text);list[i]=student;〃把学生添加到列表中i++;}privatevoidbtnSave_Click(objectsender,EventArgse)(stringfile=ザd:\Cff程序设计、student.dat”;Streamstream=newFileStream(file,Fi1eMode.OpenOrCreate,FileAccess.Write);BinaryFormatterbf=newBinaryFormatterO;〃创建序列化对象bf.Serialize(stream,list);〃把学生列表序列化并写入流 80stream.CloseO;)privatevoidbtnShow_Click(objectsender,EventArgse)(stringfile=@"d:\C#程序设计\student.dat”;Streamstream=newFileStream(file,Fi1eMode.Open,FileAccess.Read);BinaryFormatterbf=newBinaryFormatter();〃创建序列化对象StudentListstudents=(StudentList)bf.Deserialize(stream);〃把流反序列化intk=0!=null)〃逐个显示学生数据while(students[k]strings_no=students[k].student_no;stringname=students[k].name;stringdepart=students[k].department;stringresult=String.Format(*{0}\t{1}\t{2}*,s_no,name,depart);IbResult.Items.Add(result);k++;}stream.CloseO;}}【实例8-4]usingSystem;usingSystem.ComponentModel;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.10;usingSystem.Runtime.Serialization.Formatters.Binary;namespaceMyWinApppublicpartialclassfrmDemo:FormpublicfrmDemo()InitializeComponent();privatevoidbtnOpen_Click(objectsender,EventArgse)(openFileDialogl.ShowDialo晨);〃显示打开文件对话框 81privatevoidopenFileDialogl_FileOk(objectsender,CancelEventArgse)(txtFile.Text=openFileDialogl.FileName;〃返回选中的文件名Streamstream=openFileDialogl.OpenFile();〃打开选中的文件BinaryFormatterbf=newBinaryFoimatter();〃创建序列化对象StudentListstudents=(StudentList)bf.Deserialize(stream);〃把流反序列化intk=0;while(students[k]!=nul1)〃逐个显示学生列表中的数据stringsno=students[k].studentno;stringname=students[k].name;stringdepart=students[k].department;stringresult=String.FormatC{0}\t{1}\t{2}*,s_no,name,depart);IbResult.Items.Add(result);k++;}stream.CloseO;}}}【实例8-5】publicpartialclassfrmDemo:Form(privateStudentListlist=newStudentList();〃声明一个学生列表privateinti=0;//i用来标记即将加入列表中的学生,也代表学生的个数privatevoidbtnAdd_Click(objectsender,EventArgse)(Studentstudent=newStudent(txtNo.Text,txtName.Text,txtDepart.Text);list[i]=student;〃把学生添加到列表中i++;privatevoidbtnSave_Click(objectsender,EventArgse)(saveFileDialogl.ShowDialogO;}privatevoidsaveFileDialogl_FileOk(objectsender,CancelEventArgse)(Streamstream=saveFileDialogl.OpenFile();BinaryFormatterbf=newBinaryFormatter();〃创建序列化对象bf.Serialize(stream,list);〃把学生列表序列化并写入流stream.CloseO;1blShow.Text="恭喜,数据已成功保存!'n”;1blShow.Text+="文件名为:"+saveFileDialogl.FileName;) 82}【实例8-6]privatevoidbtnBrowse_Click(objectsender,EventArgse)DialogResultresult=folder.ShowDialogO;if(result==DialogResult.OK)txtPostion.Text=folder.SelectedPath;privatevoidbtnOk_Click(objectsender,EventArgse)(stringpath=string.Format(@*(0)\{1).txt*,txtPostion.Text,txtName.Text);Streamstream=newFileStream(path,FileMode.OpenOrCreate,Fi1eAccess.Write);StreamWritersw=newStreamWriter(stream);sw.Write(txtContent.Text);sw.CloseO;stream.CloseO;}privatevoidbtnCancel_Click(objectsender,EventArgse)(this.CloseO;【实例9-1】usingSystem;usingSystem.Collections.Generic;usingSystem.Text;namespaceConsoleApplicationl{publicclassMyException:ApplicationException(publicMyException(){}publicMyException(stringstrl):base(strl){}publicMyException(stringstrl,Exceptione):base(strl,e){}}classProgram(staticvoidMain(string[]args){System.Console.WriteLine(*);thrownewMyException("这是ー个自定义的异常");〃抛出ー个异常,后面将讲到})【实例9-2】usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.10;namespaceConsoleApplicationlclassProgramstaticvoidMain(string[]args) 83(StreamWriterstr=null;try(str=newStreamWriter(newFileStream(*D:\dou.txt*,FileMode.CreateNew));}catch(FileNotFoundExceptionel)(Console.WriteLine(*filenotfound*);)catch(Exceptione){Console.WriteLine(e);)finally〃不管是否捕获异常,都必须执行(Console.WriteLine(*excutefinally*);if(str!=null)str.CloseO;)}))【实例10-11usingSystem.Threading;namespaceConsoleApplicationl{classFirstThread(publicvoidTaskO〃定义了一个简单任务(Console.WriteLine(*ThisisaTask*);}staticvoidMain(string[]args)(FirstThreadft=newFirstThreadO;Threadtl=newThread(newThreadStart(ft.Task));//创建线程tl.Start0:〃启动线程Console.Read(); 84【实例10-21usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Threading;namespaceConsoleApplicationl(classMylnterrupt{publicstaticThreadsleeper;publicstaticThreadawaker;publicvoidSleepThread0(for(inti=1;i<10;i++)(Console.Write(i+;if(i==4|Ii==8)(Console.WriteLine("Threadissleepat"+i);Thread.Sleep(20);〃暂停线程publicvoidAwakeThread()(for(inti=10;i<20;i++)(Console.Write(i+",");if(sleeper.Threadstate=System.Threading.ThreadState.WaitSleepJoin)(Console.WriteUne("Threadisawakeat*+i);sleeper.Interrupt0;〃中断线程)))staticvoidMain(string[]args)(Mylnterruptmi=newMylnterrupt();sleeper=newThread(newThreadStart(mi.SleepThread));〃创建第一个线程awaker=newThread(newThreadStart(mi.AwakeThread));〃创建第二个线程sleeper.Start();//启动第一个线程awaker.Start();〃后动笫:个线程Console.Read。;【实例10-3]usingSystem;usingSystem.Collections.Generic; 85usingSystem.Text;usingSystem.Threading;namespaceConsoleApplicationl{classMyData{publicvoidShowData(Stringdata)(for(inti=1;i<500;i++)(Console.Write(data);//重要代码区}))classMyMonitor{publicstaticMyDatadb=newMyDataO;publicstaticvoidFirstThreadO(db.ShowData(*1*);}publicstaticvoidSecondThread()(db.ShowData(*2*);}staticvoidMain(string[]args)(Threadtl=newThread(newThreadStart(FirstThread));//创建线程tlThreadt2=newThread(newThreadStart(SecondThread));〃创建线程t211.StartO;〃启动11t2.StartO;〃后动t2Console.Read();)}}【实例10-41usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Threading;//引入System.Threading命名空间namespaceConsoleApplicationl{classMyThread(publicvoidLongTaskl()( 86for(inti=0;i<1000;i++)Console.WriteLineC*LongTasklisbeingexecuted!*);)publicvoidLongTask2()(for(inti=0;i<1000;i++)Console.WriteLine(*LongTask2isbeingexecuted!*);}staticvoidMain(string[]args){MyThreadtd=newMyThreadO;for(inti=0;i<50;i++)(Threadtl=newThread(newThreadStart(td.LongTaskl));〃创建线程tltl.StartO;/Z独ノ启动线程11Threadt2=newThread(newThreadStart(td.LongTask2));〃创建线程t2t2.StartO;//独立启动线程t2}Console.ReadO;})}usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Threading;namespaceConsoleApplication2(classMyThreadpool(publicvoidLongTaskl(objectobj)(for(inti=0;i<1000;i++)Console.WriteLine("LongTasklisbeingexecuted!*");pub1icvoidLongTask2(objectobj)for(inti=0;i<1000;i++)Console.WriteLine(*LongTask2isbeingexecuted!*);}staticvoidMain(string[]args){MyThreadPooltp=newMyThreadPool():〃创建线程池for(inti=0;i<50;i++)(ThreadPool.QueueUserWorkItem(newWaitCallback(tp.LongTaskl));ThreadPool.QueueUserWorkItem(newW'aitCallback(tp.LongTask2));/Z将两个任务分别添加到线程池中,并启动ThreadPool类) 87Console.ReadO;))【实例12-1】privatevoidbutton1Click(objectsender,EventArgse)(/Z数据库连接字符串stringconnString="DataSource=.;InitialCatalog=pubs;UserID=sa";/Z创建Connection对象SqlConnectionconnection=newSqIConnection(connString);/Z打开数据库连接connection.Open();MessageBox.Show("打开数据库连接成功");/Z关闭数据库连接connection.CloseO;MessageBox.Show("关闭数据库连接成功");)【实例12-2]privatevoidbutton2_Click(objectsender,EventArgse)(stringconnString="DataSource=.;InitialCatalog=pubs;UserID=sa";SqlConnectionconnection=newSqIConnection(connString);stringsql="SELECTCOUNT(*)FROMtitles"J〃SQL语句connection.OpenO;/Z打开数据库连接SqlCommandcommand=newSqICommand(sql,connection);//创建Command对象intnum=(int)command.ExecuteScalarO;//执行笹询语句,返回书冃总数stringmessage=String.Format("共有{0}木书",num);MessageBox.Show(message,"查询结果",MessageBoxButtons.OK,McssageBoxIcon.Information);connection.CloseO;(【实例11-3】privatevoidbutton3_Click(objectsender,EventArgse)(stringconnString="DataSource=.;InitialCatalog=pubs;UserID=sa";SqlConnectionconnection=newSqlConnection(connString);stringsql="updatetitlessetprice-price・。.9”;〃SQL语句connection.Open();/Z打开数据库连接SqlCommandcommand=newSqlCommand(sql,connection);//仓リ建Command对象intcount=command.ExecuteNonQuery0;//执行更新命令,返回值为更新的行数if(count>0)(stringmessage=Siring.Format("更新成功,共有{〇}本书降价",count);MessageBox.Show(message,“更新成功",MessageBoxButtons.OK,MessageBoxIcon.Information);)else( 88MessageBox.Show("没有可降价的图书","无更新",MessageBoxButtons.0K,MessageBoxIcon.Information);)(【实例12-41privatevoidbutton4_Click(objectsender,EventArgse){listBoxl.Items.ClearO;stringconnString="DataSource=.;InitialCatalog=pubs;UserID=sa";SqlConnectionconnection=newSqlConnection(connString);stringsql="SELECTtitleFROMtitles";SqlCommandcommand=newSqlCommand(sql,connection);connection.Open0;〃调用Command对象的ExecuteReader()创建DataReader对象SqlDataReaderdataReader=command.ExecuteReader();〃循环读出所有的书口名,并添加到书口列表框中while(dataReader.ReadO)(stringtitle=dataReader["title*].ToStringO;listBoxl.Items.Add(titie);}dataReader.CloseO;【实例I2-5]publicpartialclassDataSetFrm:FormSqlDataAdapterdataAdapter;DataSetdataSet;publicDataSetFrmO{InitializeComponent();))privatevoidbuttonl_Click(objectsender,EventArgse){stringconnString="DataSource=.;InitialCatalog=pubs;UserID=sa";SqlConnectionconnection=newSqlConnection(connString);stringsql="SELECT*FROMtitles";SqlDataAdapterdataAdapter=newSqlDatciAdapter(sql,connection);DataSetdataSet=newDataSet("MyData");dataAdapter.Fill(dataSet);dataGridViewl.DataSource=dataSet.Tables[0];}privatevoidbutton2__Click(objectsender,EventArgse)(SqlCommandBuiIderbuiIder=newSqlCommandBuiIder(dataAdapter);dataAdapter.Update(dataSet,"MyTable");} 89【实例12-71privatevoidbtnYes_Click(objectsender,EventArgse)(stringuserName=txtName.Text;stringpassword=txtPwd.Text;stringconnString=©"DataSource=YJ\SQI.EXPRESS;InitialCatalog二MySchool;IntegratedSecurity=True";SqlConnectionconnection=newSqlConnection(connString);〃获取用户名和密码匹配的行的数量的SQL语句stringsql=String.Format("selectcount(*)from[User]whereuserName='{0}'andpassword-,⑴,userName,password);try(connection.Open();/Z打开数据库连接SqlCommandcommand=newSqlCommand(sql,connection);//创建Commandヌす象intnum=(int)command.ExecuteScalar();〃执行査询语句,返冋匹配的行数if(num>0)(〃如果有匹配的行,则表明用户名和密码正确MessageBox.Show("欢迎进入成绩管理系统!","登录成功",MessageBoxButtons.OK,MessageBoxIcon.Information);MainFrmmainForm=newMainFrmO;/Z创建主窗体对象 90mainForm.Show();/Z显示窗体this.Visible=false;/Z登录窗体隐藏else(MessageBox.Show("您输入的用户名或密码借误!”,"登录失败”,MessageBoxButtons.OK,MessageBoxIcon.Exclamation);|)catch(Exceptionex)(MessageBox.Show(ex.Message,”操作数据库出错!",MessageBoxButtons.OK,MessageBoxIcon.Exc1amation);finally(connection.CloseO;/Z关闭数据库连接【实例12-81privatevoidbtnYes_Click(objectsender,EventArgse)(stringsex=*";if(rdoMale.Checked)sex=rdoMale.Text;elsesex=rdoFemale.Text;stringdept=cboDept.Selectedltem.ToStringO;stringspec=!stSpec.Selectedltem.ToString();stringhobby=*";if(checkBoxl.Checked)hobbyif(checkBox2.Checked)hobbyif(checkBox3.Checked)hobbyif(checkBox4.Checked)hobbyif(checkBox5.Checked)hobbyif(checkBox6.Checked)hobbystringconnString+=checkBoxl.Text;+="、"+checkBox2.Text;+="、"+checkBox3.Text;+="、"+checkBox4.Text;+="、"+checkBox5.Text;+="、"+checkBox6.Text;@"DataSource=YJ\SQI.EXPRESS;InitialCatalog=MySchool;IntegratedSecurity=True*;SqlConnectionconnection=newSqlConnection(connString);stringsql二String.Format("INSERTINTOStudentMsg(StudentName,sex,department,speciality,Hobby)VALUES(f{〇}','{1}','{2}','{3}','{4}')",txtName.Text,sex,dept,spec,hobby);〃SQL语句connection.Open();/Z打开数据库连接,SqlCommandcommand二newSqlCommand(sql,connection);//仓リ建Commandヌ寸象intcount=command.ExecuteNonQuery();/Z执行添加命令,返回值为更新的行数if(count>0)( 91MessageBox.Show("添加学生信息成功","添加成功”,MessageBoxButtons.OK,MessageBoxIcon.Information);)else(MessageBox.Show("添加学生信息失败","添加失败",MessageBoxButtons.OK,MessageBoxIcon.Information);}}catch(Exceptionex)(MessageBox.Show(ex.Message,"操作数据库出错!",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);}finally(connection.Close。;〃关闭数据库连接))【实例12-9]privatevoidbtnYes_Click(objectsender,EventArgse)(intisRequired=rdoRequired.Checked?1:0;stringconnString=©"DataSource=YJ\SQLEXPRESS;InitialCatalog-MySchool;IntegratedSecurity=True";SqlConnectionconnection=newSqlConnection(connString);stringsql=String.Format("INSERTINTOCourseMsg(CourseName,CourseClass,Required,Credit,PrelectionCredit,Experimentcredit)VALUES('{0}','⑴','⑵','⑶','{4}','{5}')",courseName,courseClass,isRequired,credit,pre1ectionCredit,ExperimentCredit);try(connection.OpenO;/Z打开数据库连接SqlCommandcommand=newSq1Command(sql,connection);〃创建Command对象intcount=command.ExecuteNonQuery();/Z执行更新命令,返回值为更新的行数if(count>0)(MessageBox.Show("添加课程信息成功","添加成功”,MessageBoxButtons.OK,MessageBoxIcon.Information);else'、レ…;ハ.Show("添加课程信息失败","添加失败",ヽ"sizBoxBuiio心.0K,MessageBoxIcon.Information);)}catch(Exceptionex)(MessageBox.Show(ex.Message,”操作数据库出错!”,MessageBoxButtons.OK,MessageBoxIcon.Exclamation);finally(connection.CloseO;/Z关闭数据库连接} 92)【实例12-10]privatevoidbtnSave_Click(objectsender,EventArgse){studentMsgTableAdapter.Update(mySchoolDataSet.StudentMsg);}privatevoidbtnClose_Click(objectsender,EventArgse)(this.CloseO;}privatevoidbtnReFresh_Click(objectsender,EventArgse)(studentMsgTableAdapter.Fill(mySchoolDataSet.StudentMsg);}privatevoidtsmNewStudentClick(objectsender,EventArgse){StudentMsgFrmstudentMsgFrm=newStudentMsgFrmO;/Z创建子窗体对象studentMsgFrm.MdiParent=this;〃指定当前窗体为MDI父窗体studentMsgFrm.Show();〃打开子窗体tssMsg.Text=studentFrm.Text;〃状态栏中显示操作内容【实例12-11]privatevoidbtnSave_Click(objectsender,EventArgse){courseMsgTableAdapter.Update(mySchoolDataSet1.CourseMsg);privatevoidbtnClose_Click(objectsender,EventArgse)this.CloseO;privatevoidbtnReFresh_Click(objectsender,EventArgse)(courseMsgTableAdapter.Fill(mySchoolDataSet1.CourseMsg);}privatevoidtsmCurMsgMagClick(objectsender,EventArgse)(CourseFrmcourseFrm=newCourseFrmO;/Z创建子窗体对象courseFrm.MdiParent=this;〃指定当前窗体为ゆI父窗体courseFrm.Show();〃打开子窗体tssMsg.Text=courseFrm.Text;〃状态栏中显示操作内容}【实例12-12]publicpartialclassScoreMsgFrm:Form(DataSetds=newDataSet();stringconnString;SqlConnectionconnection;publicScoreMsgFrm()(InitializeComponent(); 93connString=-"DataSource=YJ\SQLEXPRESS;InitialCata1og=MySchoo1;IntegratedSecurity=True*;connection=newSqlConnection(connString);)//...)privatevoidBindCourseData()(stringsql="SELECTCourseId,CourseNameFROMCourseMsg";SqlDataAdapterdataAdapter=newSqlDataAdapter(sql,connection);DataSetdataSet=newDataSet();dataAdapter.Fill(dataSet);cboCourse.DataSource=dataSet.Tables[0];}privatevoidBindStudentDataO(stringsql=*SELECTStudentNo,StudentNameFROMStudentMsg*;SqlDataAdapterdataAdapter=newSqlDataAdapter(sql,connection);DataSetdataSet=newDataSet0;dataAdapter.Fill(dataSet);cboStudent.DataSource=dataSet.Tables[0];stringsql="SELECTScoreMsg.StudentNo,StudentMsg.StudentName,CourseMsg.CourseName,ScoreMsg.ScoreFROMStudentMsg,CourseMsg,ScoreMsgwhereStudentMsg.StudentNo二ScoreMsg.StudentNoandScoreMsg.CourseId=CourseMsg.Courseld";SqlDataAdapterdataAdapter=newSqlDalaAdapler(sql,connection);DataSetdataSet=newDataSet(*MyData");dataAdapter.Fill(dataSet);〃设置各列的显示数据字段dataGridViewl.Columns[0].DataPropertyName="StudentNo":dataGridViewl.Columns[1].DataPropertyName:StudentName";dataGridViewl.Columns[2].DataPropertyName=*"CourseName;dataGridViewl.Columns[3].DataPropertyName="Score;dataGridViewl.DataSource=dataSet.Tables[0];}privatevoidScoreMsgFrm_Load(objectsender,EventArgse)(BindCourseDataO;BindstudentData0;BindDataO;}privatevoidbuttonl_Click(objectsender,EventArgse)(intcourseld=(int)cboCourse.SelectedValue;intStudentNo=(int)cboStudent.SelectedValue;intscore=(int)nudScore.Value;SqlCommandcommand; 94〃是否已有该学生成绩stringsql=String.Format("selectcount(*)fromScoreMsgwhereStudentNo二{0}andCourseld={1),StudentNo,courseld);try(command=newSqlCommand(sql,connection);connection.Open0;intnum=(int)command.ExecuteScalarO;if(num>0)(〃如果已有该学生成绩,则修改学生成绩sql=String.Format("UPDATEScoreMsgSETScore={0}WHEREStudentNo=(1)ANDCourseld=(2)",score,StudentNo,courseld);〃SQL语句else〃如果没有该学生成绩,则添加学生成绩sql=String.Format(*INSERTINTOScoreMsg(StudentNo,CourseId,Score)VALUES({0},{1},{2})*,studentNo,courseld,score)1〃SQL语句connection.CloseO;connection.Open();/Z打开数据库连接,command=newSqlCommand(sql,connection);//创建Command对象intcount=command.ExecuteNonQuery();/Z执行更新命令,返回值为更新的行数if(count>0)(MessageBox.Show("更新学生成绩成功","添加成功”,MessageBoxButtons.OK,MessageBoxIcon.Information);}else(MessageBox.Show("更新学生成绩失败","添加失败",MessageBoxButtons.OK,MessageBoxIcon.Information);})catch(Exceptionex)(MessageBox.Show(ex.Message,"操作数据库出错!",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);)finally(connection.CloseO;〃关闭数据库连接BindDataO;〃重新显示学生成绩}}privatevoidbtnClose_Click(objectsender,EventArgse)(this.CloseO;}privatevoidbtnReFreshClick(objectsender,EventArgse){BindDalaO;〃重新显示学生成绩} 95privatevoidtsmCurMsgMag_Click(objectsender,EventArgse)(ScoreMsgFrmscoreMsgFrm=newScoreMsgドrm();/Z创建/窗体对象scoreMsgFrm.MdiParent=this;〃指定当前窗体为ME父窗体scoreMsgFrm.Show。;〃打开子窗体tssMsg.Text=scoreMsgFrm.Text;〃状态栏屮显示操作内容
此文档下载收益归作者所有