2013-10-08 25 views
0

我有這個類(從網上獲取):打開窗體使用辛格爾頓和參數傳遞

class SingletonFormProvider 
{ 
    static Dictionary<Type, Form> mTypeFormLookup = new Dictionary<Type, Form>(); 

    static public T GetInstance<T>(Form owner) 
     where T : Form 
    { 
     return GetInstance<T>(owner, null); 
    } 

    static public T GetInstance<T>(Form owner, params object[] args) 
     where T : Form 
    { 
     if (!mTypeFormLookup.ContainsKey(typeof(T))) 
     { 
      Form f = (Form)Activator.CreateInstance(typeof(T), args); 
      mTypeFormLookup.Add(typeof(T), f); 
      f.Owner = owner; 
      f.FormClosed += new FormClosedEventHandler(remover); 
     } 
     return (T)mTypeFormLookup[typeof(T)]; 
    } 

    static void remover(object sender, FormClosedEventArgs e) 
    { 
     Form f = sender as Form; 
     if (f == null) return; 

     f.FormClosed -= new FormClosedEventHandler(remover); 
     mTypeFormLookup.Remove(f.GetType()); 
    } 
} 

如果使用標準的開放,我知道如何傳遞參數:

 Form f = new NewForm(parameter); 
     f.Show(); 

但我使用這種方式打開新窗體(在上述類的幫助下):

 var f = SingletonFormProvider.GetInstance<NewForm>(this); 
     f.Show(); 

那麼,怎樣才能以這種方式打開新窗體的參數?

請幫忙。

謝謝。

+0

你是什麼意思的參數? –

+0

參數,變量,對象 – Iyas

+0

像這樣:Form f = new NewForm(textBox1.Text); f.Show(); – Iyas

回答

0

GetInstance<T>方法有一個params對象[]參數在最後。它基本上說,你可以繼續給它的參數,他們將被放入object[]給你。

該方法在調用Activator.CreateInstance時將這些參數傳遞給表單的構造函數。

不幸的是,您的參數只會在第一次創建時傳遞給該子表單,而不是每次表單被顯示,因爲正在創建的表單將與其類型進行緩存。如果需要在子窗體上顯示一些值時,我建議在該窗體上創建一個Initialize方法,該方法接受您需要設置的參數。

public class NewForm : Form 
{ 
    ... 

    public NewForm(string constructorMessage) 
    { 
     //Shows the message "Constructing!!!" once and only once, this method will 
     //never be called again by GetInstance 
     MessageBox.Show(constructorMessage); 
    } 

    public void Initialize(string message) 
    { 
     //Shows the message box every time, with whatever values you provide 
     MessageBox.Show(message); 
    } 
} 

調用它像這樣

var f = SingletonInstanceProvider.GetInstance<NewForm>(this, "Constructing!!!"); 
f.Initialize("Hi there!"); 
f.Show(); 
+0

SO告訴我要避免像「+1」或「thanks」這樣的評論,但我無法抗拒。謝謝! – Iyas