一个干净的方式来分享一些状态(在钥匙你的情况字典)是通过一些共享服务(单身),所以:
你可以创建一个类(如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/)... –