一個乾淨的方式來分享一些狀態(在鑰匙你的情況字典)是通過一些共享服務(單身),所以:
你可以創建一個類(如ElectrodeManager
)將舉行的電極字典(首先是空的)。
在Form1你將填充該字典通過指定的方法對類(例如AddElectrode(string electrodeType, string electrodeKey)
- >這將增加新項到字典) - 所以你將不得不Dictionary<string, string>
保持例如{「T1」,「K000-000」},{「T2」,「K000-0001」} ...
在Form2中,您將從ElectrodeManager
工作該字典,並將字符串從文本框追加到電極的關鍵。
例子:
public class ElectrodeManager
{
#region Singleton Pattern
private static ElectrodeManager instance;
public static ElectrodeManager Instance
{
get
{
if (instance == null)
instance = new ElectrodeManager();
return instance;
}
}
private ElectrodeManager()
{
electrodes = new Dictionary<string, string>();
}
#endregion
#region Fields
private Dictionary<string, string> electrodes;
#endregion Fields
#region Methods
public void AddElectrode(string eType, string eKey)
{
if (!electrodes.ContainsKey(eType))
{
electrodes.Add(eType, eKey);
}
}
public void AppendStringToElectrodeKey(string eType, string keyAddendum)
{
string electrodeKey = String.Empty;
if (electrodes.TryGetValue(eType, out electrodeKey))
{
electrodes[eType] = String.Format("{0}-{1}", electrodes[eType], keyAddendum);
}
}
public IDictionary<string, string> GetElectrodes()
{
return electrodes;
}
#endregion Methods
}
內Form1上(在生成邏輯的地方)使用方法:
ElectrodeManager.Instance.AddElectrode("T1", "K000-000");
ElectrodeManager.Instance.AddElectrode("T2", "K000-001");
內部窗體2(點擊按鈕):
ElectrodeManager.Instance.AppendStringToElectrodeKey("T1", textBox.Text);
ElectrodeManager.Instance.AppendStringToElectrodeKey("T2", textBox.Text);
當然,你可以很容易地如果更適合您,請將數據類型切換到List<string>
。
將一個構造函數添加到'Form2',它將一個'List'作爲參數。當你創建你的'Form2'時,把'List '實例作爲參數傳遞給那裏。 'Form2'還需要一個屬性來存儲列表,通過'Form1'訪問,或者通過引用傳遞它也應該工作。只需在表單之間搜索傳遞對象/值;這已被問無數次。 –
sab669
[Duplicate 1](http://stackoverflow.com/questions/3062575/)[duplicate 2](http://stackoverflow.com/questions/7800731/)[duplicate 3](http://stackoverflow.com/問題/ 17032484 /)[duplicate 4](http://stackoverflow.com/questions/17836398/)[duplicate 5](http://stackoverflow.com/questions/25316230/)[duplicate 6](http:// stackoverflow.com/questions/29092707/)... –