您的位置:首页 > 编程语言 > C#

C#面向对象基础(二) 构造与析构 欢乐农场篇

2011-09-06 10:36 459 查看
构造方法,特殊的方法.

名称与类名相同
无返回值(其实返回地是一个对象)

在你的类末定义构造方法时,有一个空的构造方法(你看不到看不到)

为什么要构造方法? 你用类创建一个对象时,直接做好一些事情,比如,把名字起好,年龄设置好... 这就是构造能帮你做的.

下面为Animal类加入构造方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConApp
{
/// <summary>
/// 动物(农场里的)
/// </summary>
public class Animal
{
// 字段 存储这些数据
public string name;
public int age;
public bool ishungry;
public float price;

public Animal()
{
Console.WriteLine("Animal构造了");
}
//构造方法重载 overload
public Animal(string name)
{
this.name = name;
}
public Animal(string n, int a)
{
name = n;
age = a;
}

public void ShowInfo()
{
Console.WriteLine("动物 姓名{0} 年方{1}",name,age);
Console.WriteLine("当前位置 x:{0} y:{1}",x,y);
}
}
}

解释一下this

this.name = name; this 指的是当前实例,什么是"当前实例"?你在构造鸡的时候,当然实例就是鸡,你构造羊,当前实例就是羊... 第二个name ,是构造方法的参数.千万别混了!

使用构造方法

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ConApp
7 {
8 /// <summary>
9 /// 农场
10 /// </summary>
11 public class Farm
12 {
13 public Animal cock;
14 public Animal goat;
15 public Animal cow;
16 public Animal rabbit;
17
18 /// <summary>
19 /// 构造方法 开始建农场了 初始化
20 /// </summary>
21 public Farm()
22 {
23 Console.WriteLine("农场开始构造 building....");
24
25 cock = new Animal("cock",1);
26 goat = new Animal("xiyangyang",3
);
27
28 cock.price =2;
29 cock.ishungry = true;
30
31 goat.price = 3;
32 goat.ishungry = false;
33
34 Console.WriteLine("农场初始化成功");
35 }
36
37 public void ShowAnimals()
38 {
39 cock.ShowInfo();
40 goat.ShowInfo();
41 }
42 }
43 }

析构方法

析构,就是解构.构造方法负责建对象析构负责销毁对象.

析构方法 在构造方法前面加个~ 不能有参数 不加访问修饰符

怎么调用? 你不能调用, CLR自动执行的. 在对象应该消失的时候...

来看下Animal的析构

//析构
~Animal()
{
Console.WriteLine("析构 {0}",name);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: