现在的位置: 首页 > 综合 > 正文

第4课:类的设计

2012年07月26日 ⁄ 综合 ⁄ 共 1311字 ⁄ 字号 评论关闭

构造函数

构造函数间的调用 :this(参数列表)

public BankCustomer(string fn, string ln, double bal)
{
	this.firstName = fn;
	this.lastName  = ln;
	this.balance   = bal;
} 

public BankCustomer(string fn, string ln)  // start with 0.0 balance
	: this(fn, ln, 0.0)
{ }

属性
用于封装私有字段,(命名规则:一般是属性大写,字段小写)

索引器
用于封装私有数组:命名:public 返回值类型 this[int  索引变量]

using System;

namespace WindowsApplication2
{
private Person[] relatives;

public Person this [int index]
{
	get
	{
		return relatives[index];
	}
	set
	{
		if (value != null)
		{
			relatives [index] = value;
		}
	}
}
} 

代理/委托

分类:一般委托、多播委托 
委托是一个类,其定义和方法类似,定义如下

 public delegate double DelegateCompute(double x); 

声明一个委托实例引用,并初始化实例

DelegateCompute dc;
dc= new DelegateCompute(Form1.Low); //实例化一个Low方法的代理 

下面是用委托来调用方法

double result;
result = MoneyCompute.Compute(1000.0,dc); //返回值给result变量

多播委托

引用多个方法的委托,它连续调用多个方法
为了把委托的单个实例合并成一个多播委托,委托必须是同类型的,返回类型必须是void、不能带输出参数(可以带引用参数)
多播委托应用于事件模型中 

事件委托 

定义:

public delegate void NameListEventHandler(object source, WindowsApplication5.NameListEventArgs args); 

声明:

NameList names =new NameList(); //NameList类,内含nameListEvent事件委托实例的引用声明如下:
//public event NameListEventHandler nameListEvent;
names.nameListEvent += new NameListEventHandler(NewName); //初始化事件委托实例
names.nameListEvent += new NameListEventHandler(CurrentCount);
names.Add("MSDN");//调用方法Add,Add方法内含委托方法的调用
names.Add("Webcast");

调用:

//NameListEventArgs为派生于EventArgs的事件数据类
nameListEvent(this, new NameListEventArgs(name, list.Count));

事件 clone close&dispose XML

抱歉!评论已关闭.