public class Class2 { public string Name; public Class2(string AName) { Name = AName; if(instanceList!=null) { instanceList.Add(this); } } public static System.Collections.ArrayList instanceList = new System.Collections.ArrayList(); } public class TestClass2 { public static void Test() { Class2 cl = new Class2("c1"); Class2 c2 = new Class2("c2"); Class2 c3 = new Class2("c3"); for(int i=0;i<Class2.instanceList.Count;i++) { Class2 tmp = Class2.instanceList[i] as Class2; System.Windows.Forms.MessageBox.Show(tmp.Name); } } }
在这个类自己内部实现就很简单,在构造函数中把this指针保存在一个静态集合里好像就可以了
{
public string Name;
public Class2(string AName)
{
Name = AName;
if(instanceList!=null)
{
instanceList.Add(this);
}
}
public static System.Collections.ArrayList instanceList = new System.Collections.ArrayList();
}
public class TestClass2
{
public static void Test()
{
Class2 cl = new Class2("c1");
Class2 c2 = new Class2("c2");
Class2 c3 = new Class2("c3");
for(int i=0;i<Class2.instanceList.Count;i++)
{
Class2 tmp = Class2.instanceList[i] as Class2;
System.Windows.Forms.MessageBox.Show(tmp.Name);
} }
}
{
private Hashtable m_Hashtable=new Hashtable(30);
public static readonly lockTable=new lockTable();
public void Add(object Value)
{
WeakReference obj=new WeakReference(Value); } public void Destory(object Value)
{
}
}
public class lockTable
{
private Hashtable m_Hashtable;
public static readonly lockTable Instance = new lockTable();
Timer timer; public lockTable()
{
m_Hashtable=new Hashtable(30);
timer=new Timer(60*1000);
timer.Enabled=true;
timer.Elapsed+=new ElapsedEventHandler(timer_Elapsed);
}
public void Add(object Value)
{
WeakReference obj=new WeakReference(Value);
//这里可以改为数据库的Pk或其他的可标记的标记,如果使用HashCode,需要重写GetHashCode的方法
lock(m_Hashtable)
{
m_Hashtable.Add(Value.GetHashCode(),obj);
} } public void Destory(object Value)
{
WeakReference obj=(WeakReference)m_Hashtable[Value.GetHashCode()];
if(obj.IsAlive)
{
obj.Target=null;
lock(m_Hashtable)
{
m_Hashtable.Remove(Value.GetHashCode());
}
}
} private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
IEnumerator tors=this.m_Hashtable.Keys.GetEnumerator();
while(tors.MoveNext())
{
WeakReference obj=(WeakReference)m_Hashtable[tors.Current];
if(!obj.IsAlive)
{
lock(m_Hashtable)
{
m_Hashtable.Remove(tors.Current);
}
} } }
}