C#面向对象编程(续)2009-05-31 本站 L小凤一.构造函数上次说到类是封装了属性和方法的实体的集合,面向对象编程过程把所有的东西都看成对象,而且世界上没有一模一样的对象,所以在创建对象的时候要对对象的属性进行初始化.在定义基本类型变量的时候.声明一个对象的方法如下:int myint = 3;但是在创建对象型数据的时候要用到关键字new来完成对象的创建.最基本的string类型对象的创建方法如下:string name = new string("Lu xiaofeng");这里在调用name的时候内存中会加载 name=”Lu xiaofeng”.对象型数据必须在创建后才能使用,否则会出现错误一下:可能尚未初始化变量.另一个比较重要的概念就是构造函数,每一个类都有一个默认的构造函数来初始化对象的一些数据.同时要注意的是构造函数的形式:
| 构造函数的函数名必须与类的名字相同,而且是没有任何返回值,也不允许用void来修饰.但是构造函数允许重载:一个类中可以用多个不同的构造函数来满足创建对象.例如在Person类中有两个构造函数: public Person(){}构造函数 |
和public Person(String name,String sex,int age,double weight)//构造函数.当我们在定义一个Person类的变量的时候; Person myman=new Person();同时也可以用另一个构造函数来初始化一个对象.Person niu=new Person("name","man",22,99);但是这个对象和myman对象是不一样的.但是这两个对象的属性是不一样.

二.this的引用我们先来看下两个构造函数的具体内容:
public Person() {name = "Lu xiaofeng";sex = "man";age = 22;weight = 99;} | public Person(string name, string sex, int age, double weight) { this.name = name;this.sex = sex;this.age = age;this.weight = weight;}//构造函数二 |
在第二个构造函数中多了个this,this的作用是用来指定”这个”的.尤其是在下面的情况:public string name public string sex;public int age;public double weight;这四个字段的名字与构造函数public Person(string name, string sex, int age, double weight)的参数一样的时候.this是用来指定当前这个对象的.当然我们可以把public Person(string name, string sex, int age, double weight)的参数换成其他的名字. public Person(string myname, string mysex, int myage, double myweight).这个并不会影响程序的结果,但是如果把上表构造函数二中的中的this去掉,来看看有甚么影响.创建两个对象.person1,person2.Person newman = new Person("lixiao", "woman", 11, 88);Console.WriteLine("name={0},sex={1},age={2},weight={3}",newman.name, newman.sex, newman.age, newman.weight);Person another = new Person();Console.WriteLine("name={0},sex={1},age={2},weight={3}",another.name, another.sex, another.age, another.weight);Console.ReadKey();
public Person(string name, string sex, int age, double weight){name = name;sex = sex;age = age;weight = weight;}//去掉 this后. | |

去掉this后的效果.有关this的知识在后面还会介绍. 现在对this做个简单的小节:this关键字引用被访问成员所在的当前实例。静态成员函数没有this指针。this关键字可以用来从构造函数,实例方法和实例化访问器中访问成员。本文发表于编程入门网(bianceng.cn)不能在静态方法。静态属性访问器或者域声明的变量初始化程序中使用this关键字,这将会产生错误。1.在类的构造函数中出现的this作为一个值类型表示对正在构造的对象本身的引用。2.在类的方法中出现this作为一个值类型表示对调用该方法的对象的引用。3.在结构的构造函数中出现的this作为一个变量类型表示对正在构造的结构的引用。4.在结构的方法中出现的this作为一个变量类型表示对调用该方法的结构。