WinForm缓存机制

来源:互联网 发布:文泰软件baiduyun 编辑:程序博客网 时间:2024/06/06 02:05

本人才疏学浅,幸得高人相助,在第一次发表文章之际,向他表示衷心地感谢!

首先定义一个类

 using System;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;

namespace WinFormTest
{
    public class FormCache
    {
        private static System.Collections.Hashtable ht = new System.Collections.Hashtable();

        public static System.Windows.Forms.Form GetForm(string formtype)
        {
            if (ht.Contains(formtype))
            {

            }
            else
            {
                ht.Add(formtype, System.Activator.CreateInstance(System.Type.GetType(formtype)));
            }
            Form temp= ht[formtype] as Form;
            temp.FormClosing += new FormClosingEventHandler(temp_FormClosing);
            return temp;

        }

        public static System.Windows.Forms.Form GetForm(string formtype,object[] obj)
        {
            if (ht.Contains(formtype))
            {

            }
            else
            {
                Type type=System.Type.GetType(formtype);
                //object obj2=System.Activator.CreateInstance(type, obj, null);
                //object obj3 = System.Activator.CreateInstance(type, obj);
                ht.Add(formtype, System.Activator.CreateInstance(type,obj));
            }
            Form temp = ht[formtype] as Form;
            temp.FormClosing += new FormClosingEventHandler(temp_FormClosing);
            return temp;

        }

        static void temp_FormClosing(object sender, FormClosingEventArgs e)
        {
          
            Form f = sender as Form;
            f.Hide();
            e.Cancel = true;
            //throw new Exception("The method or operation is not implemented.");
        }
    }
}

调用代码是:

        private void button1_Click(object sender, EventArgs e)
        {
            FormCache.GetForm("WinFormTest.Form2").Show();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FormCache.GetForm("WinFormTest.Form3",new object[1]{"123"}).Show();
        }

原创粉丝点击