visual C#.NET程序设计

第一章 C#.NET基础概念
1 面向机器编程 面向过程编程 面向对象编程
2 UML图
3 CLR公共语言运行库 CLS公共语言运行规范 MSIL微软中间语言 CTS通用类型系统 SDK利用文本编译器编写代码然后编译和运行 IDE可视化开发环境
4 helloWord
`using System;

class firstProgram
{
public static void Main(string[ ] args)
{
Console.WriteLine(“My First C# Program!”);
}
}`
5 帮助文档
第二章 C#语言基础
1关键字与标识符
2标识符的命名
变量 骆驼 dtNum
布尔类型 isStackFull
接口 ICalculatble
其他 pascal DtNum
3注释
4值类型与引用类型相等的概念
值类型
类型和数值相等即相等
引用类型
类型,数值,引用地址相等即相等
5变量,常量,文字
常量用const创建
6数据类型
7运算符
8类型转换
9装箱与拆箱
10顺序结构 选择结构 循环结构
11跳转语句
continue跳出本次循环
break跳出循环结构
goto跳转到指定位置
12数组与Array类
13String和StringBuilder
14格式化与ToSring
第三章 C#面向对象程序设计
1类与对象
类中的常量必须在声明的同时初始化
用类名.常量名调用
不能用static修饰
用readonly修饰只读字段
2构造函数
构造函数

using System;
public class Test4Constructor
{
    private string studName;
    private int studID;
    private string Department;
    public Test4Constructor()
    { }
    public Test4Constructor(string strName)
    {
        studName = strName;
    }
    public Test4Constructor(string strName, int ID, string dept) : this(strName)
    //利用this关键字调用第2个构造函数
    {
        studID = ID;
        Department = dept;
    }
    public void FindInfo(int id)
    {
        if (id == studID)
            Console.WriteLine("{0}is a student in the {1}Department ", studName, Department);
    }
}
public class Test
{
    public static void Main()
    {
        Test4Constructor FindAnExample = new Test4Constructor("张三", 0518288, "计算机");
        FindAnExample.FindInfo(0518288);
        Test4Constructor FindExample = new Test4Constructor("张三");
        FindExample.FindInfo(0);
    }
}

静态的构造函数

	using System;
	class MyClass
	{
	     public static int staticInt ;
	     static MyClass() 
	      {  Console.WriteLine(staticInt);
	         Console.WriteLine("The static constructor invoked.");
	         staticInt=1;
	      }
	      /*
	      1静态函数只被调用一次
	      2静态成员被引用之前,创建第一个实例之前,静态成员初始化之后,将自动调用静态构造函数 
	      */
	     public static void MyMethod()
	     {   Console.WriteLine("MyMethod invoked.");
	     }
	}
	class MainClass
	{
	    static void Main() 
	    {    Console.WriteLine(MyClass.staticInt);
	        MyClass.MyMethod();
	    }
	}

3析构函数
4属性
基本用法
属性体现了面向对象的封装性

	using System;
	namespace School
	{	
		public class Student
		{
			string studName;
			int studID;
			string Department;
			//定义了一个属性,封装了studName字段
	        public string StudentName
	        {	get{return studName;}
	            set{studName=value;}
	        }
	    }
	    public	class Test
	    {	
	static void Main(string[] args)
		    {  Student AStudent = new Student();
		       AStudent.StudentName="Li Si";
		       string aName = AStudent.StudentName;
		       //系统按照属性出现在语句中的位置,自动选择调用get或set
		       Console.WriteLine(aName);
		     }
	    }
	}

属性的读写控制

	using System;
	namespace School
	{	
		public class Student
		{
			string studName;
			int studID;
			string Department;
			public Student ( ) { }
			public Student(string strName)
			{   studName=strName;	}
	        public string StudentName
	        {	get{return studName;}
	        }
	    }
	    public	class Test
	    {	
	static void Main(string[] args)
		    {  Student AStudent = new Student("Li Si");
		       string aName = AStudent.StudentName;
		       //外皆可以获取studName字段的值却无法改变他
		       Console.WriteLine(aName);
		     }
	    }
	}

在属性中完成更多的功能


	using System;
	namespace School
	{	
		public class Student
		{
			string studName;
			int studID;
			string Department;
	//构造函数
			public Student ( ) { }
			public Student(string strName)
			{   studName=strName;	}
			public Student(string strName,int ID,string dept):this(strName)
			{studID=ID;  Department=dept;}		
			//属性
	public string StudentName
			{ get{return studName;}
			}
			public int StudentID
			{ set{studID=value;}
	}
			//完成更多字段输出的属性,和字段不必一一对应
	public string StudentInfo		
	        {  get{ return "Student Name is "+studName+"\nStudentID is "+studID+"\nDepartment is "+Department;}	
			}
	    } 
	    //测试类
		public	class Test
		{	
	static void Main(string[] args)
			{    Student AStudent = new Student("Li Si",200501001,"Computer");
			  	AStudent.StudentID=200501011;
				string aName = AStudent.StudentName;
				Console.WriteLine(aName);
				Console.WriteLine(AStudent.StudentInfo);
			}
		}
	}

静态属性
静态属性是访问静态字段或方法的属性,访问器中的数据成员只能是静态的,用类名.属性进行访问
5索引器


	using System;
	namespace TestOfIndexer
	{
	public class IndexerTesting
	{
	int theInt;
	string str;
	int [] IntArray=new int[3];
	
	public IndexerTesting()
	{}
	public IndexerTesting(int[] iArr)
	{IntArray=iArr;
	}
	public int IntAccessor
	{   get{return theInt;}
		set{ theInt=System.Math.Abs(value);}
		}
	public string TheString
	{	get { return str;}
	set{ str=value+DateTime.Now;}
	}
	//定义索引器(存在数组的对象使用索引器才是简便有效的)
	public int this[int ind]
	{  get { return IntArray[ind];}
		}	
		//索引器的重载
	public int this[ char chInStr]
	{  get { return str.IndexOf(chInStr);}
	}
	}
	  public class Test
	  {
	static void Main(string[] args)
	{  int [] iArr={2,3,4};
	IndexerTesting IndTesting=new IndexerTesting(iArr);
		Console.WriteLine("IntArray[{0}] is {1} ",2,IndTesting[2]);
		//IndTesting[2]为使用索引器
		IndTesting.IntAccessor=-365;
		Console.WriteLine(IndTesting.IntAccessor);
		IndTesting.TheString ="Create time:";
		Console.WriteLine(IndTesting.TheString);
		Console.WriteLine("-是第{0}个字符,",(IndTesting['-']+1));
		//IndTesting['-']为使用索引器
	    }
	}
	}

6对象的复制
浅复制

//程序7-9
using System;
class Student 
{
	public int studID;
	public string studName;
}

class CollegeStudent: Student 
{
	public int DepartmentID;
	public CollegeStudent ShallowCopy()
	{	return (CollegeStudent)MemberwiseClone();
	}

}
public class Test
{
	public static void Main() 
	{	CollegeStudent S1 = new CollegeStudent();
		S1.studID = 2003179;
		S1.studName = "Sam";
		S1.DepartmentID=001;
		CollegeStudent S2 = S1.ShallowCopy();
		Console.WriteLine(S2.studID+"  "+S2.studName);
	}
}

深复制

//程序7-10
using System;
class Student 
{
	public int studID;
	public string studName;
}
public class Department
{
	public int DepartmentID;
	public Department()
	{ }
	public Department(int i)
	{	DepartmentID=i;
	}
}

class CollegeStudent: Student,ICloneable 
{       
 	public Department Dept;
	public CollegeStudent(string nm, int sID, int dID)
	{	studID=sID;
		studName=nm;
		Dept= new Department( dID);
	}
	public object Clone()
	{	CollegeStudent CS=new CollegeStudent(this.studName, this.studID,this.Dept.DepartmentID);
		return CS;
	}
}
public class Test
{
	public static void Main() 
	{	CollegeStudent S1 = new CollegeStudent( "Sam",2003179,001);
		CollegeStudent S2 = (CollegeStudent)S1.Clone();
		S1.studName="Bush";
		S1.Dept.DepartmentID=002;
		Console.WriteLine(S1.studID+"  "+S1.studName+"  "+S1.Dept.DepartmentID );
		Console.WriteLine(S2.studID+"  "+S2.studName+"  "+S2.Dept.DepartmentID );
		Console.WriteLine(Object.ReferenceEquals(S1,S2));
		//程序7-10
using System;
class Student 
{
	public int studID;
	public string studName;
}
public class Department
{
	public int DepartmentID;
	public Department()
	{ }
	public Department(int i)
	{	DepartmentID=i;
	}
}

class CollegeStudent: Student,ICloneable 
{       
 	public Department Dept;
	public CollegeStudent(string nm, int sID, int dID)
	{	studID=sID;
		studName=nm;
		Dept= new Department( dID);
	}
	public object Clone()
	{	CollegeStudent CS=new CollegeStudent(this.studName, this.studID,this.Dept.DepartmentID);
		return CS;
	}
}
public class Test
{
	public static void Main() 
	{	CollegeStudent S1 = new CollegeStudent( "Sam",2003179,001);
		CollegeStudent S2 = (CollegeStudent)S1.Clone();
		//
		S1.studName="Bush";
		S1.Dept.DepartmentID=002;
		Console.WriteLine(S1.studID+"  "+S1.studName+"  "+S1.Dept.DepartmentID );
		Console.WriteLine(S2.studID+"  "+S2.studName+"  "+S2.Dept.DepartmentID );
		Console.WriteLine(Object.ReferenceEquals(S1,S2));
		//深复制后2个对象的引用已不再相等
	}
}

7值传递,引用传递,ref参数

//程序8-1
using System;
namespace ParametersPassing
{
	public class ParamsPassing
	{              char [] ChArr;
		//构造函数
                                public ParamsPassing ()
		{}
		public ParamsPassing (char[] ch)
		{  ChArr=ch;
		}
		public ParamsPassing(ref char[] ch)
		{ChArr = ch;}
		 //测试用属性
                                public char MyChArr                
                                { get{ return ChArr[1];}
                                  set{ ChArr[1] = value;}
                                 }
		//测试用方法
                                //值类型参数,值传递
                                public int Sum(int x, int y)
		{	Console.WriteLine("Before Calculating, x={0},  y={1}",x,y);
			x ++;
			y ++;
			Console.WriteLine("After Calculating,  x={0},  y={1}",x,y);
			return x+y;    
		}
		//值类型参数,引用传递
		public void Swap( ref int x,ref int y)
		{   Console.WriteLine("Before  Swapping x={0},  y={1}",x,y);
		    int temp;
		    temp=x;
			x=y;
			y=temp;
			Console.WriteLine("After Swapping x={0},  y={1}",x,y);
		}
		//引用类型参数,“值传递”和引用传递
		public void ArrParams(int[] ValArr, ref int [] RefArr)
		{   Console.WriteLine("In the method:");
			Console.Write("Before calculating,the ValArr's elements are:");
			foreach(int elem in ValArr)Console.Write(elem+", ");Console.WriteLine();
			ValArr[0]=123;
			ValArr=new int[]{-1,-2,-3};
			Console.Write("After calculating the ValArr's elements are:");
		                foreach(int elem in ValArr)Console.Write(elem+", ");Console.WriteLine();
			Console.Write("Before calculating,the RefArr's elements are:");
			foreach(int elem in RefArr)Console.Write(elem+", ");Console.WriteLine();
			RefArr[0]=456;
			RefArr=new int[]{-4,-5,-6};
			Console.Write("After calculating,the RefArr's elements are:");
			foreach(int elem in RefArr)Console.Write(elem+", ");Console.WriteLine();
                                               Console.WriteLine("Leave the method");
		}
	}
	public class Test
	{
		public static void Main ()
		{
			ParamsPassing AnExample =new ParamsPassing();
			//测试值类型参数的值传递
                                                int value1=5;
			int value2=10;
                                                Console.WriteLine("调用值传递方法前value1 = {0},  value2 = {1}", value1, value2);
			int theSum=AnExample.Sum(value1, value2);
			Console.WriteLine("Sum= "+theSum);
			Console.WriteLine("调用值传递方法后value1 = {0},  value2 = {1}", value1, value2);
                                                //测试引用传递
                                               Console.WriteLine("调用引用传递方法前value1 = {0},  value2 = {1}", value1, value2);
                                               AnExample.Swap(ref value1,ref value2);
                                               Console.WriteLine("调用引用传递方法后value1 = {0},  value2 = {1}", value1, value2);
			//测试引用类型参数的“值传递”和引用传递
			int[] FirArr = {101,102,103};
			int[] SecArr={201,202,203};
			Console.Write("测试前,数组FirArr的元素为:");
			foreach(int elem in FirArr)Console.Write(elem+", ");
                                                Console.WriteLine();
			Console.Write("测试前,数组SecArr的元素为:");
			foreach(int elem in SecArr)Console.Write(elem+", "); 
                                               Console.WriteLine();
			AnExample.ArrParams(FirArr,ref SecArr);
			Console.Write("测试后,数组FirArr的元素为:");
			foreach(int elem in FirArr)Console.Write(elem+", ");Console.
                                                WriteLine();			
			Console.Write("测试后,数组SecArr的元素为:");
			foreach(int elem in SecArr)Console.Write(elem+", ");
                                               Console.WriteLine();
		               char[]cc={'a','b','c','d'};
			ParamsPassing AnotherExample=new ParamsPassing(cc);
			Console.WriteLine("测试前,ChArr[1]是:"+AnotherExample.MyChArr);
                                                cc[1]='f';
			Console.WriteLine("实参cc[1]修改为f后,ChArr[1]为:"+AnotherExample.MyChArr);
		                AnotherExample.MyChArr='w';
                                                Console.WriteLine("ChArr[1]修改为w后,cc[1]的值为:"+cc[1]);
			char[]dd = {'a','b','c','d'};
			ParamsPassing The3rdExample=new ParamsPassing(ref dd);
			Console.WriteLine("测试前,ChArr[1]是:"+The3rdExample.MyChArr);
                                                dd[1]='m';
			Console.WriteLine("实参dd[1]修改为m后,ChArr[1]为:"+The3rdExample.MyChArr);
		                The3rdExample.MyChArr='s';
                                                Console.WriteLine("ChArr[1]修改为s后,实参dd[1]的值为:"+dd[1]);
                                      }

	}
}

8params参数和out参数

//程序8-1
using System;
namespace ParametersPassing
{
	public class ParamsPassing
	{              char [] ChArr;
		//构造函数
                                public ParamsPassing ()
		{}
		public ParamsPassing (char[] ch)
		{  ChArr=ch;
		}
		public ParamsPassing(ref char[] ch)
		{ChArr = ch;}
		 //测试用属性
                                public char MyChArr                
                                { get{ return ChArr[1];}
                                  set{ ChArr[1] = value;}
                                 }
		//测试用方法
                                //值类型参数,值传递
                                public int Sum(int x, int y)
		{	Console.WriteLine("Before Calculating, x={0},  y={1}",x,y);
			x ++;
			y ++;
			Console.WriteLine("After Calculating,  x={0},  y={1}",x,y);
			return x+y;    
		}
		//值类型参数,引用传递
		public void Swap( ref int x,ref int y)
		{   Console.WriteLine("Before  Swapping x={0},  y={1}",x,y);
		    int temp;
		    temp=x;
			x=y;
			y=temp;
			Console.WriteLine("After Swapping x={0},  y={1}",x,y);
		}
		//引用类型参数,“值传递”和引用传递
		public void ArrParams(int[] ValArr, ref int [] RefArr)
		{   Console.WriteLine("In the method:");
			Console.Write("Before calculating,the ValArr's elements are:");
			foreach(int elem in ValArr)Console.Write(elem+", ");Console.WriteLine();
			ValArr[0]=123;
			ValArr=new int[]{-1,-2,-3};
			Console.Write("After calculating the ValArr's elements are:");
		                foreach(int elem in ValArr)Console.Write(elem+", ");Console.WriteLine();
			Console.Write("Before calculating,the RefArr's elements are:");
			foreach(int elem in RefArr)Console.Write(elem+", ");Console.WriteLine();
			RefArr[0]=456;
			RefArr=new int[]{-4,-5,-6};
			Console.Write("After calculating,the RefArr's elements are:");
			foreach(int elem in RefArr)Console.Write(elem+", ");Console.WriteLine();
                                               Console.WriteLine("Leave the method");
		}
	}
	public class Test
	{
		public static void Main ()
		{
			ParamsPassing AnExample =new ParamsPassing();
			//测试值类型参数的值传递
                                                int value1=5;
			int value2=10;
                                                Console.WriteLine("调用值传递方法前value1 = {0},  value2 = {1}", value1, value2);
			int theSum=AnExample.Sum(value1, value2);
			Console.WriteLine("Sum= "+theSum);
			Console.WriteLine("调用值传递方法后value1 = {0},  value2 = {1}", value1, value2);
                                                //测试引用传递
                                               Console.WriteLine("调用引用传递方法前value1 = {0},  value2 = {1}", value1, value2);
                                               AnExample.Swap(ref value1,ref value2);
                                               Console.WriteLine("调用引用传递方法后value1 = {0},  value2 = {1}", value1, value2);
			//测试引用类型参数的“值传递”和引用传递
			int[] FirArr = {101,102,103};
			int[] SecArr={201,202,203};
			Console.Write("测试前,数组FirArr的元素为:");
			foreach(int elem in FirArr)Console.Write(elem+", ");
                                                Console.WriteLine();
			Console.Write("测试前,数组SecArr的元素为:");
			foreach(int elem in SecArr)Console.Write(elem+", "); 
                                               Console.WriteLine();
			AnExample.ArrParams(FirArr,ref SecArr);
			Console.Write("测试后,数组FirArr的元素为:");
			foreach(int elem in FirArr)Console.Write(elem+", ");Console.
                                                WriteLine();			
			Console.Write("测试后,数组SecArr的元素为:");
			foreach(int elem in SecArr)Console.Write(elem+", ");
                                               Console.WriteLine();
		               char[]cc={'a','b','c','d'};
			ParamsPassing AnotherExample=new ParamsPassing(cc);
			Console.WriteLine("测试前,ChArr[1]是:"+AnotherExample.MyChArr);
                                                cc[1]='f';
			Console.WriteLine("实参cc[1]修改为f后,ChArr[1]为:"+AnotherExample.MyChArr);
		                AnotherExample.MyChArr='w';
                                                Console.WriteLine("ChArr[1]修改为w后,cc[1]的值为:"+cc[1]);
			char[]dd = {'a','b','c','d'};
			ParamsPassing The3rdExample=new ParamsPassing(ref dd);
			Console.WriteLine("测试前,ChArr[1]是:"+The3rdExample.MyChArr);
                                                dd[1]='m';
			Console.WriteLine("实参dd[1]修改为m后,ChArr[1]为:"+The3rdExample.MyChArr);
		                The3rdExample.MyChArr='s';
                                                Console.WriteLine("ChArr[1]修改为s后,实参dd[1]的值为:"+dd[1]);
                                      }

	}
}

9局部变量

//程序7-10
	using System;
	public class Range
	{
		public int X;
		public void RangeTesting (int i)
		{   int X;
		    X=i;//局部变量要赋值后才能使用
		    for(int j =i; j<6; j++){X+=j;Console.WriteLine("在代码块中X="+X);}
	                    Console.WriteLine("离开代码块,仍在方法中,X="+X);
 	                    Console.WriteLine("离开代码块,仍在方法中,字段X="+this.X);
                                }
		public void TestingAgain()
		{  Console.WriteLine("离开隐藏过X的方法,仍在类中,X="+X);
		}
	    public static void Main()
		{   Range t1=new Range();
			t1.RangeTesting(3);
		    t1.TestingAgain();
		    Console.WriteLine("在Main方法中,X="+t1.X);
	    }
	}

10签名与重载
11main方法
12运算符重载
一元运算符重载

//程序8-5
using System;
public struct Complex 
{
	public double real;
	public double imaginary;
	public Complex(double rea, double img) //构造函数
	{	real = rea;
		imaginary = img;
	}
	public static Complex operator - (Complex clx)
	{	return new Complex (-clx.real,-clx.imaginary);	
	}
	public static Complex operator ++(Complex clx)
	{	clx.real+=1;
		clx.imaginary+=1;
		return clx;
	}
	public static bool operator true(Complex clx)
	{	return (clx.real>0);
	}
	public static bool operator false(Complex clx)
	{	return (clx.real<=0);
	}
}
public class Test
{
	public static void Main()
	{	Complex CP=new Complex(2,3);
		CP=-CP;
		CP++;
		Console.WriteLine("Real= {0}\n"+"Imaginary= {1}",CP.real,CP.imaginary);
		if (CP)Console.WriteLine("The real part is positive.");
			else Console.WriteLine("The real part is not positive.");
	}
}

二元运算符重载

//程序8-6
using System;
public struct Complex 
{
	public int real;
	public int imaginary;
	public Complex(int real, int imaginary) 
	{	this.real = real;
		this.imaginary = imaginary;
	}
	public static Complex operator +(Complex c1, Complex c2) 
	{	return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
	}
	public static Complex operator - (Complex c1, Complex c2) 
	{	return new Complex(c1.real - c2.real, c1.imaginary - c2.imaginary);
	}
}
public class Test
{
	public static void Main() 
	{	Complex num1 = new Complex(1,2);
		Complex num2 = new Complex(3,4);
		Complex sum = num1 + num2;
		num2-=num1;
		Console.WriteLine("First complex number:  {0}+{1}i",num1.real,num1.imaginary);
		Console.WriteLine("Second complex number: {0}+{1}i",num2.real,num2.imaginary);
		Console.WriteLine("The sum of the two numbers: {0}+{1}i",sum.real,sum.imaginary);
	}
}

类型转换运算符重载

//程序8-7
using System;
public struct Unicode
{
	char chvalue;
	public Unicode(int value)                                       //构造函数
	{	if (value < 0 || value >char.MaxValue) throw new ArgumentException();
		chvalue = (char)value;
	}
	public static implicit operator int(Unicode Uni)     //隐式转换运算符
	{	return Uni.chvalue;
	}
	public static explicit operator Unicode(int i)    //显式转换
	{	return new Unicode(i);						  
	}
}
public class Test
{
	public static void Main()
	{	int a =6691;
		Unicode d =(Unicode) a;
		int b = d;
		Console.WriteLine(b);
	
	}
}

13类的继承
基类与派生类

//程序9-1
using System;
namespace School
{
	public class Student 
	{
		protected string studName;
		protected	int studID;
		public Student()
		{  }
		public Student(string str, int id)
		{	studName=str;
		     	studID=id;
		}
                                public void PrintBase()
		{Console.WriteLine("在基类: Student.");
		}
		public void FindInfo(int id)
		{	if(id==studID)
			Console.WriteLine ("{0}is a student. ", studName);
		}
	} 
	public class CollegeStudent :Student
	{        
                         string department; 
                         new string  studName; 
	         public CollegeStudent(string deptmnt,string str, int id)
	         {  	department=deptmnt;
		studName=str;
		studID=id;
	          }
                          public void PrintDerived()
	          {Console.WriteLine("在派生类: CollegeStudent.");
	          }
	          public  new void FindInfo(int id)
	          //new关键字表示继承,有和没有都无所谓
	          {	if(id==studID)
		Console.WriteLine ("{0}is a student in the {1} Department. ", studName,department);
	          }
	}
	public class Test
	{
	   public static void Main()
	   {             Student AStudent = new Student("李四",0518277);
		 CollegeStudent CollegeStudent=new CollegeStudent("计算机","张三", 0518288);
		 AStudent.FindInfo(0518277);
		 AStudent.PrintBase();
		 CollegeStudent.FindInfo(0518288);
		 CollegeStudent.PrintBase();
		 CollegeStudent.PrintDerived();
	   }
	}
}

成员的继承,添加,隐藏

//程序9-2
	using System;
	namespace School
	{
	public class Student 
	{
	protected string studName;
		protected	int studID;
		public Student()
		{  }
		public Student(string str, int id)
		{  studName=str;
		   studID=id;
		}
		public void PrintBase()
		{  Console.WriteLine("在基类: Student.");
		}
		public void FindInfo(int id)
		{  if(id==studID)
		   Console.WriteLine ("{0}is a student. ", studName);
		   //基类的studName通过子类的构造函数base.studName=bStudName;赋值
		}
	} 
	public class CollegeStudent :Student
	{        
	string department; 
		new string  studName; 
		//隐藏基类的同名成员
		public CollegeStudent ( string deptmnt,string str,string bStudName, int id )
	{  	   department=deptmnt;
		   studName=str;
		   studID=id;
		   base.studName=bStudName;
		}
	public void PrintDerived()
		{  Console.WriteLine("在派生类: CollegeStudent.");
		}
		public  new void FindInfo(int id)
		{  if(id==studID)
	   Console.WriteLine ("{0}is a student in the {1} Department. ", studName,department);
		}
		public  void FindInfo2(int id)
		{  if(id==studID)
	   Console.WriteLine ("{0}is a student in the {1} Department. ", base.studName,department);
		}
	    public   void FindInfo3(int id)
		{  if(id==studID) base.FindInfo( id);
		}
	}
	public class Test
	{
	public static void Main()
		{  Student AStudent = new Student("李四",0518277);
	       CollegeStudent ACollegeStudent=new CollegeStudent ("计算机","张三", "王二",0518288);
		   AStudent.FindInfo(0518277);
		   AStudent.PrintBase();
		   ACollegeStudent.FindInfo(0518288);    //输出派生类的studName
		   ACollegeStudent.FindInfo2(0518288);   //输出基类的studName
	       ACollegeStudent.FindInfo3(0518288);   //调用基类的FindInfo方法
		   ACollegeStudent.PrintBase();          //从派生类调用基类的方法
		   ACollegeStudent.PrintDerived();       //从派生类调用派生类的方法
		}
	}
	}

关键字base
利用base调用父类的构造方法
在派生类中间接的调用父类的被隐藏的方法
14访问控制符
无访问修饰符则默认的认为是private
继承private和protected成员

//程序9-3
	using System;
	public class BasCls
	{
		protected int x;
		public void Func( BasCls a, DerCls1 b, DerCls2 c)
		{  a.x = 1;
		   b.x = 1;
		   //  c.x=1;
		   // c.y=1;
		   Console.WriteLine("a.x={0}  b.x={1}  c.x={2}", a.x,b.x,c.x);
		}
	}
	public class DerCls1: BasCls
	{
		public void Func(BasCls a, DerCls1 b)
		{  //a.x = 1;
		   b.x = 4;
		}
	}
	public class DerCls2: BasCls 
	{
		new protected int x;
		protected int y=9;
		public DerCls2( )
		{ }
		public DerCls2(int i)
		{   base.x=i;
		}
		public int TheX
		{get{return x ;}
		 set {x=value;}
		}
	}
	public class ATrial
	{
		public static void Main()
		{   BasCls aa = new BasCls ( );
		    DerCls1 bb = new DerCls1( );
		    DerCls2 cc = new DerCls2(6);
		    cc.TheX=8;
		    Console.WriteLine("the x in cc="+cc.TheX);
		    aa.Func(aa,bb,cc);
		    //调用为父类赋值过的X
		}
	}

15嵌套类和对象成员

//程序9-4
using System;
namespace School
{
		public class Students
	{
		protected int studID;
		protected string studName;
		protected string department;
		Teacher TeacherA;
		Courses CourseX;
		public Students()
		{}
		public Students(int id, string name,string cname)
		{	studName=name;
			studID=id;
			CourseX=new Courses(cname);
		}
		public Students(int id, string name,int tID,string tname)
		{       	studID=id;
			studName=name;
			TeacherA=new Teacher(tID,tname);
			
		}
		public Students(int id, string name,Teacher tt)
		{       	studID=id;
			studName=name;
			TeacherA=tt;
			
		}
		public void TheStudent()
		{Console.WriteLine("ID: {0}, NAME: {1} ",studID,studName);
		}
		public void TheTeacher()
		{	Console.WriteLine("The teacher is "+TeacherA.TheTeacher);
		}
		public void TheCourse()
		{	Console.WriteLine("The course is "+CourseX.courseName);
		}
		public class Courses                      //嵌套类
		{	
			internal string courseName;
			public Courses()
			{}
			public Courses(string cname)
			{courseName=cname;
			}
			public void CourseInfo()
			{	Console.WriteLine("The new course is:"+courseName);	
			}
		}
	}
	public class Teacher       //非嵌套类
	{
		int teacherID;
		string teacherName;
		public string TheTeacher
		{get{return teacherName;}
		}
		public Teacher()
		{}
		public Teacher(int i, string name)
		{teacherID=i;  teacherName=name;
		}
	
	}
	public class Test
	{
		public static void Main()
		{
			Students StudentA=new Students(123,"Zhang san","C++ Programming");
			StudentA.TheStudent();
			StudentA.TheCourse();
			Students.Courses NewCourse=new Students.Courses("Visual C# Programming");
			NewCourse.CourseInfo();
			Students StudentB=new Students(0503111,"Alan",0911,"Bush");
			StudentB.TheStudent();
			StudentB.TheTeacher();
			Teacher Professor=new Teacher(0032, "Andrew");
			Students StudentC=new Students(789,"Davel",Professor);
			StudentC.TheStudent();
			StudentC.TheTeacher();
		}
	}
}

16as运算符进行类型转换

//程序9-5
using System;
namespace School
{
	public class Student 
	{
		protected string studName;
		protected	int studID;
		public Student()
		{  }
		public Student(string str, int id)
		{
			studName=str;
			studID=id;
		}
		public string TheName
		{ get { return studName;}
		}
		public void PrintBase()
		{
			Console.WriteLine("在基类: Student.");
		}
		public void FindInfo(int id)
		{
			if(id==studID)
			Console.WriteLine ("{0}is a student. ", studName);
		}
	} 
	public class CollegeStudent :Student
	{        
		string department; 
		public CollegeStudent(string deptmnt,string str, int id):base(str,id)
		{
			department=deptmnt;
		}
		public void PrintDerived()
		{
			Console.WriteLine("在派生类: CollegeStudent.");
		}
		public  new void FindInfo(int id)
		{
			if(id==studID)
			Console.WriteLine ("{0}is a student in the {1} Department. ", studName,department);
		}
	}
	public class Test
	{
		public static void DisplayCls(Student stu)
		{Console.WriteLine("Base or Derived class? "+stu.ToString());
		}
		public static void DisplayObj(Student stu)
		{Console.WriteLine("The Student Name is "+stu.TheName);
		}
		public static void Main()
		{
			Student StudentA = new Student("李一",0518244);
			Student StudentB = new CollegeStudent("计算机","王二",0518255); 	//注意:基类的引用,派生类的空间
			Student StudentC = new Student("张三",0518266);
			Student StudentD = new CollegeStudent("计算机","刘四",0518277);
			CollegeStudent CollegeStudentA=new CollegeStudent("计算机","赵五", 0518288);
			CollegeStudent CollegeStudentB=new CollegeStudent("计算机","陈六", 0518299);
			StudentA = CollegeStudentA;    //允许
			//CollegeStudentA = StudentB;    //错误
			DisplayObj(StudentC);
			DisplayObj(CollegeStudentB);  //形参是基类对象,实参为派生类对象
			DisplayCls(StudentC);
			DisplayCls(CollegeStudentB);  //形参是基类对象,实参为派生类对象
			CollegeStudentB = (CollegeStudent) StudentB;
			//CollegeStudentB = (CollegeStudent) StudentC;	//编译通过,运行时错误
			CollegeStudent CollegeStudentC;
		    	CollegeStudentC= StudentC as CollegeStudent;
			CollegeStudent CollegeStudentD = StudentD as CollegeStudent;
			if(CollegeStudentC==null)Console.WriteLine("CollegeStudentC is null");
			if(CollegeStudentD!=null)Console.WriteLine("CollegeStudentD is not null");
			CollegeStudentD.FindInfo(0518277);
		}
	}
}

17抽象类与封闭类
封闭类为最终类用sealed修饰
18多态
多态基础
虚成员表示要被重写用virtual修饰
注意隐藏和重写

//10-1
using System;
class A
{   
	public void Func() { Console.WriteLine("Func() in A"); }
	public virtual void VO() { Console.WriteLine("BaseClass.VO()"); }
}
class B:A
{
	public int j;
	new public  void Func() { j=2; Console.WriteLine("Func() in B,  the new member = "+j); }
	public override void VO() { j=2; Console.WriteLine("VO() in B, the new member = "+j);  }
	public void FromBase(){ base.VO();}
}
class C:B
{
	public int k;
	new public  void Func() { k=3; Console.WriteLine("Func() in C, the new member = "+k); }
	public override void VO() {k=3; Console.WriteLine("VO() in C, the new member = "+k); }
}
class D:C
{
	public int m;
	new public  void Func() { m=4; Console.WriteLine("Func() in D, the new member = "+m); }
	new public virtual void VO() { m=4; Console.WriteLine("VO() in D, the new member = "+m);}
}
class E:D
{
	public int n;
	new public  void Func() { n=5; Console.WriteLine("Func() in E, the new member = "+n); }
	public override void VO() { n=5; Console.WriteLine("VO() in E, the new member = "+n);}
}
class Test
{
	static public void VirtualandOverride(A a)
	{
		a.Func();
		a.VO();
	}
	static void Main() 
	{
		A aa= new A();     //基类对象aa
		A ab = new B();    //或者A ab = bb;  基类对象,引用指向派生类对象
		B bb = new B();    //派生类对象bb
		ab.Func();		   //调用非虚方法,输出:“Func() in A”
		bb.Func();		   //调用非虚方法,输出:“Func() in B, the new member = 2”
		aa.VO();		   //输出:“BaseClass.VO()”
		//Console.WriteLine(ab.j);		//错误:A中并不包含对j的定义
		ab.VO();		   //调用虚方法,输出:“VO() in B, the new member = 2”。ab中没有j,但却通过覆盖的方法使用了j
		bb.VO();		   //调用虚方法,输出:“VO() in B, the new member = 2”
		bb.FromBase();		   //输出:“BaseClass.VO()”,表明虽然覆盖了基类的VO(),但是基类的VO()仍然存在
		Console.WriteLine(ab.ToString());//输出:“B”,ab的类型是B?
		//B ba=ab;        //错误: 无法将类型“A”隐式转换为“B”,ab到底是不是B类型?
		Console.WriteLine("Testing");
		VirtualandOverride(aa);
		VirtualandOverride(ab);
		A ac =new C();
		VirtualandOverride(ac);		
		A ad =new D();
		VirtualandOverride(ad);
		A ae=new E();
		VirtualandOverride(ae);
		
	}
}

多态

//程序10-2
using System;

namespace School
{
	public class Student
	{ 
		protected string studName;
		public Student()
		{}
		public Student(string name)
		{
			studName=name;
			
		}
		public virtual string TheName
		{
			get{return studName;}
		}
		public virtual void PhyEdu()
		{
			Console.WriteLine("  In good health.");
        }
		public virtual void Commonweal()
		{
			 Console.WriteLine("  Be of virtue.");
		}
		public virtual void GradePointAverage()
		{
			Console.WriteLine("  The GPA is very high.");
		} 
	
	}
	public class CompStudent:Student
	{ 
		double gpa;
		int Comnweal;
		double phy;
		public CompStudent()
		{}
		public CompStudent(string name, int c, double p,double g):base(name)
		{
			studName=name;
			Comnweal=c;
			phy=p;
			gpa=g;
		}
		public override string TheName
		{
			get{return studName;}
		}
		public override void Commonweal()
		{
			if(Comnweal>=40) Console.WriteLine("  Always helps others.");
		}
		public override void GradePointAverage()
		{
			if(gpa>=3.5)Console.WriteLine("  Excellent GPA: {0} ", gpa);
			
		} 
	
	}
	public class ArtStudent:Student
	{ 
		double gpa;
		int Comnweal;
		double phy;
		public ArtStudent()
		{}
		public ArtStudent(string name, int c, double p,double g):base(name)
		{
		studName=name;
		Comnweal=c;
		phy=p;
		gpa=g;
		}
		public override string TheName
		{
			get{return studName;}
		}
		public override void PhyEdu()
		{
			if(phy>=3.5)	Console.WriteLine("  Good at sports.");
		}
		public override void Commonweal()
		{
			if(Comnweal>=50) Console.WriteLine("  Full of artist's virtue.");
		}
	}
	public class Test
	{
		public static void Evaluate(Student stu)
		{
			Console.WriteLine("The student's name is "+stu.TheName);
			stu.Commonweal();
			stu.PhyEdu();
			stu.GradePointAverage();
		}
		public static void Main()
		{
			Student [] Students=new Student [2];
			Students[0]=new CompStudent("Li",50,3.8,3.7);
			Students[1]=new ArtStudent("Zhang",82,3.5,3.9);
			foreach(Student stud in Students )Evaluate(stud);
		}
	}
}

ToString()的重写

//程序10-3
using System;
public class Student	
{
	protected string   studName;
	protected int      ID;
	protected string   contactPhone;
	public Student(string i ,int j, string k)
	{ 	studName = i ;
		ID = j ;
		contactPhone = k;		
	}
}
public class CollegeStudent : Student
{
	public CollegeStudent(string i,int j,string k) :base(i,j,k)
	{ }
	public override string ToString()
	{
		return studName;
	}
}
class Test
{
	static void Main(string[] args)
	{
		Student StudentA = new Student("maggie",2000379,"56335568");
		CollegeStudent StudentB = new CollegeStudent ("maggie",2000379,"56335568");
		Console.WriteLine (StudentA);
		Console.WriteLine (StudentB);
	}
}


19接口
实现接口

//程序11-1
using System;
interface IDistributable
{
	void Distribute();
}
interface ISalable
{
	void Sale();
}
public class Print
{
	protected int num;
	protected double prc;
	public Print(){}
	public Print(int n, double p)
	{
		num=n;
		prc=p;
	}
	public void Publish ()
	{
		Console.WriteLine("Number: {0}, Price: ¥{1} ",num,prc);
	}
}
public class LectureNotes :Print, IDistributable, ISalable
{
	protected string Name;
	public LectureNotes(){}
	public LectureNotes(string nm,int n, double p):base(n,p)
	{	Name = nm; 
		//在基类构造函数中完成:
		// num=n;	prc=p;
	}
	public void Notes(){Console.WriteLine("The LectureNotes is "+Name);}
	public void Distribute(){Console.WriteLine("Distributed in campus only.");}
	public void Sale(){Console.WriteLine("Sale on cost.");}
}

public class Test
{
	public static void Main()
	{
		LectureNotes LN = new LectureNotes("C# Programming", 400, 28.6);
		LN.Notes();
		LN.Distribute();
		LN.Sale();
		LN.Publish();
		
	}
}

接口对象

///程序11-2
using System;
public interface IDisplayable
{
	void Display();
}
public class Derv1:IDisplayable
{
	public void Display(){Console.WriteLine("The Derv1");}
}
public class Derv2:IDisplayable
{
	public void Display(){Console.WriteLine("The Derv2");}
}
public class Test
{
	public static void Poly(IDisplayable d)
	{
		d.Display();
	}
	public static void Main()
	{
		IDisplayable D1=new Derv1();
		IDisplayable D2=new Derv2();
		IDisplayable D3;
		//D3=new IDisplayable();//错误: 无法创建抽象类或接口的实例
		D3=D2;  //允许
		Poly(D1);
		Poly(D2);
		Poly(D3);
	}
}

显示接口成员实现

//程序11-3
using System;
interface IDistributable
{
	void Distribute();
	void Store();
}
interface ISalable
{
	void Sale();
	void Distribute();
}
public class Publish:IDistributable,ISalable
{
	protected int num;
	protected double prc;
	public Publish()
	{}
	public Publish(int n, double p)
	{
		num=n;
		prc=p;
	}
	public void Distribute()
	{
		Console.WriteLine("Distributed in campus only.");
	}
	public void Sale()
	{
		Console.WriteLine("Sale on cost.");
	}
	void ISalable.Distribute()
	{
		Console.WriteLine("Where to distribute?");
	}
	void IDistributable.Store()
	{
		Console.WriteLine("To Store.");
	}
	public void ToPublish ()
	{
		Console.WriteLine("Number: {0}, Price: ¥{1} ",num,prc);
		//ISalable.Distribute();          //错误,无法直接调用显式接口成员实现
		((ISalable)this).Distribute();    //允许通过转换调用显式接口成员实现
	}
}
public class LectureNotes :Publish
{
	protected string Name;
	public LectureNotes()
	{}
	public LectureNotes(string nm,int n, double p):base(n,p)
	{
		Name = nm; 
		num=n;
		 prc=p;
	}
	public void Title()
	{
		Console.WriteLine("The LectureNotes Title:  "+Name);
	}
	public void ForStore()
	{
		((IDistributable)this).Store(); //在派生类中调用基类的显式接口成员实现
	}
}
public class Test
{
	public static void Main()
	{
		LectureNotes LN = new LectureNotes("C# Programming", 400, 28.6); //类对象
		ISalable ExplicitImpl = LN; //接口对象
		LN.Title();
		LN.ToPublish();
		ExplicitImpl.Distribute();      //通过接口对象调用显式接口成员实现
		((ISalable)LN).Distribute(); //通过对类对象的转换调用显式接口成员实现
		LN.Distribute();	          //通过类对象调用接口成员实现
		LN.Sale();
		LN.ForStore();
	}
}

20结构

//程序11-4
using System;
interface IBook
{ string AboutBook{get;}}
public struct Book:IBook
{
	string Title;
	string ISBN;
	public string AboutBook			//实现属性
	{
		get{return String.Concat(Title,ISBN);}
	}
	public Book(string s1, string s2)
	{
		Title=s1;
		ISBN=s2;
	}
}
public class Test
{
	public static void Main()
	{
		Book [] Books=new Book [3];
	    	Books[0]=new Book("C++ Programming ","7-801");
		Books[1]=new Book("JAVA Programming ","7-804");
		Books[2]=new Book("C# Programming ","7-810");
		foreach(Book B in Books)Console.WriteLine(B.AboutBook);
	}
}

21委托
22事件
23异常处理
第四章 C#的高级技术
第五章 C#常用类
第六章 流
第七章 windows应用程序
第八章 多线程技术
第九章 数据库访问技术
第十章 进程间通信
第十一章 ASP.NET初步

非常经典的高校C# .net开发教程,《Visual C#.NET程序设计》作者,李兰友,杨晓光,清华出版社,北交出版社,含有书籍和源码。 本书主要介绍Visual C#.NET应用程序设计技术。内容包括:Visual C#.NET集成环境,常用Windows窗体控件,工程界面设计,C#.NET程序设计基础,图形、图像处理、数据库应用、Web应用及应用程序设计实践等。在完成本书的学习和实践后,学生可以在C#的应用程序开发技能方面得到较大提高。本书可作为高等学校计算机程序设计语言课程教科书,亦适合于工程技术人员参考。 目录 第1章 Visual C#.NET集成环境 1.1 创建一个Visual C#应用程序 1.2 Visual Studio .NET主要窗口及用法 1.3 Visual Studio .NET的菜单栏和工具条 本章小结 习题 第2章 C#语言基础 2.1 数据类型 2.2 表达式 2.3 程序控制语句 本章小结 习题 第3章 C#.NET面向对象程序设计 3.1 类 3.2 接口 3.3 委托与事件 3.4 编译和调试 本章小结 习题 第4章 常用Windows窗体控件 4.1 文本控件 4.2 列表选择控件 4.3 图形显示控件 4.4 选择控件 4.5 定时控件 4.6 Button控件 本章小结 习题 第5章 Windows应用程序界面设计 5.1 命令按钮界面设计 5.2 菜单界面设计 5.3 单选按钮界面设计 5.4 MDI界面设计 5.5 工具栏界面设计 5.6 状态栏界面设计 本章小结 习题 第6章 文本编辑器设计 6.1 RichTextBox控件 6.2 通用对话框控件 6.3 文本编辑器设计 本章小结 习题 第7章 C#图形程序设计基础 7.1 GDI+绘图基础 7.2 基本图形的绘制 7.3 实用图形程序设计 本章小结 习题 第8章 VC#图像处理基础 8.1 VC#图像处理基础 8.2 图像的输入和保存 8.3 图像拷贝和粘贴 8.4 彩色图像处理 8.5 动画 本章小结 习题 第9章 数据库应用 9.1 概述 9.2 ADO.NET对象 9.3 ADO.NET编程应用示例 本章小结 习题 第10章 Web应用 10.1 ASP.NET基础 10.2 ASP.NET服务器组件 10.3 Web服务 10.4 XML 10.5 ASP.NET编程应用示例 本章小结 习题 第11章 应用程序设计实践 11.1 电子邮箱程序设计 11.2 Web浏览器程序设计 11.3 彩图处理 11.4 统计图表 11.5 五子棋 本章小结 习题 参考文献
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值