日期:2014-05-18  浏览次数:20814 次

有很多FORM类 如 Form1 Form2........Formn 分别实例化了 a1 a2 ...an,如何写通用函数通过此函数调用a1 ....an
如题 
有很多FORM类 如 Form1 Form2........Formn 分别实例化了 a1 a2 ...an,如何写通用函数通过此函数调用a1 ....an
a1到an都是单实例的 
a1..........an 通过不同的button 实现各自的SHOW 
需要判断 an 是否为空是否注销了 如是 需要重新实例

C# code


Form1 a1=new Form1();

.....

Formn an=new Formn();

private void button_Click(object sender, EventArgs e)
{
  if(a1==null||a1.Isdisposed)
{ 
 a1=new Form1();
}


}




怎么样能写个通用函数实现button按钮事件里的方法呢



------解决方案--------------------
单例模式正适合你的情况。

------解决方案--------------------
看的有点乱呀,你想关联N个表吗

------解决方案--------------------
class Form1
{
private Form1 alarmManager()
{}

public static Form1 Instance = new Form1();
}


你每次需要的时候,就调用form1的时候,就用Form1.Instance就行了
------解决方案--------------------
C# code

//单例窗体,适当改动代码
 protected void ShowMdiChild<TForm>() where TForm : Form, new()
        {
            Form child = this.MdiChildren.FirstOrDefault(frm => frm is TForm);
            if (child == null)
            {
                child = new TForm();
                child.MdiParent = this;
                child.StartPosition = FormStartPosition.WindowsDefaultLocation;
                child.WindowState = FormWindowState.Maximized;
                child.Show();

            }
            else
            {
                child.StartPosition = FormStartPosition.WindowsDefaultLocation;
                child.WindowState = FormWindowState.Maximized;
                child.Select();
            }

        }
//调用方法
private void button_Click(object sender, EventArgs e)
{
   this.ShowMdiChild<a1>();
}

------解决方案--------------------
static Hashtable arr = new Hashtable();
public static T GetInstance<T>(string className){
if (arr[className] == null){
arr[className] = (T)System.Reflection.Assembly.Load("命名空间").CreateInstance("命名空间."+className);
}
return arr[className] as T;
}
------解决方案--------------------
C# code

static Hashtable arr = new Hashtable();
public static T GetInstance<T>() where T : class {
var t = typeof(T);
var k = t.FullName;
if (arr[k] == null){
arr[k] = (T)t.Assembly.CreateInstance(t.FullName);
}
return arr[k] as T;
}