您的位置:首页 > 其它

利用委托链实现非静态变量初始化一次,但是构造函数执行多次

2012-04-06 11:26 363 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Class1
{
static void Main(System.String[] args)
{
Set.Feedback fb= new Set.Feedback(Class1.FeedbackToConsole);
for (System.Int32 i = 0; i < 5;i++ )
{
new Set(3).ProcessingItem(fb);
fb += new Set.Feedback(Class1.FeedbackToConsole);
}
Console.Read();
}
static void FeedbackToConsole(System.Object value,System.Int32 item,System.Int32 length,System.Int32 id)
{
Console.WriteLine("{4},Processing item[{1}] of {2}:{0}-----Set[{3}]",value,item,length,id,Set.times++);
}
}

class Set
{
private System.Object[] items;
private System.Int32 _id=0;
public static System.Int32 times=1;

public System.Int32 Id
{
get
{
return this._id;
}
set
{
this._id = value;
}
}

public Set(System.Int32 numItem)
{
times = 1;
this._id = Identify.id++;
Console.WriteLine("产生新的实例{0}",this._id);
items = new System.Object[numItem];
for (System.Int32 i = 0; i < numItem;i++ )
{
items[i] = i;
}
}
public delegate void Feedback(System.Object value,System.Int32 item,System.Int32 itemLenth,System.Int32 id);
public void ProcessingItem(Feedback feedback)
{
if(feedback!=null)
{
for (System.Int32 i = 0; i < items.Length;i++ )
{
feedback(items[i],i+1,items.Length,this._id);
}
}
}
}

class Identify
{
public static System.Int32 id = 0;
}

}

执行结果:



总结:

1,利用属性和外加静态int32可以区分同一个类的不同实例;

2,利用静态字段和构造函数初始化可以实现一个实例的一个方法执行次数的统计;

3,利用委托可以实现具体方法实现的分离,实现约束方法签名,方法实现多态化。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: