问题描述
我有类似的问题早先几天的,但现在是比较复杂的。
I had similar problem few days earlier but now is more complicated.
我试图使用ArrayList从表格2,在表格1。我不能创建窗体2的一个新实例,因为它会让我的表2空的内容。我怎么会改变我的一片code的做到这一点?
I am trying to use ArrayList from form 2, in form 1. I can not create a new instance of form 2 because it will make my content of form 2 null. How could I do this by changing my piece of code?
傻瓜例子建议。
修改
int totalEntries = 0;
var myarr = SharedResources.Instance.ArrayList;
if(cmbType.SelectedIndex == 0)
myarr.Add(new AddPC(cmbType.Text,
txtUserName.Text, txtPassword.Text));
为什么会高于code引起的NullReferenceException?
Why would above code cause nullreferenceexception?
private void sfdSaveToLocation_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
EncryptDecrypt en = new EncryptDecrypt();
StringBuilder sb = new StringBuilder();
// I need the arraylist here but I can not access it as it is.
foreach (var list in addWindow.addedEntry)
{
if (list is AddPC)
{
AddPC tmp = (AddPC)list;
sb.Append(tmp.ToString());
}
else if (list is AddWebSite)
{
AddWebSite tmp = (AddWebSite)list;
sb.Append(tmp.ToString());
}
else if (list is AddSerialCode)
{
AddSerialCode tmp = (AddSerialCode)list;
sb.Append(tmp.ToString());
}
}
File.WriteAllText(sfdSaveFile.FileName, sb.ToString());
}
我已经有AddEntryWindow形式的新实例这里:
I already have new instance of AddEntryWindow form here:
private void tsmiAddEntry_Click(object sender, EventArgs e)
{
if (storedAuth == null)
{
DialogResult result = MessageBox.Show
("You must log in before you add an entry."
+ Environment.NewLine + "You want to authenticate?",
"Information", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
AuthenticationWindow authWindow =
new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
else
{
}
}
else
{
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
问候。
推荐答案
这是思路可以创建只能有一个实例三分之一singletone类
数组列表,股吧所以在你的应用程序的每个类都可以使用它。
An idea can be creating third singletone class that only can have one instance ofarray list and shares it so every class in your app can use it
public class ShareArray
{
private System.Collections.ArrayList arrayList;
#region Property
public System.Collections.ArrayList ArrayList { get{return arrayList;}}
#endregion
#region Imp. signletone
private static ShareArray instance;
public static ShareArray Instance
{
get
{
if (instance == null)
{
instance = new ShareArray();
}
return instance;
}
}
private ShareArray()
{
arrayList = new System.Collections.ArrayList();
}
#endregion
}
和在那里你这样想使用这个类中的每个
and use this class every where you want in this way
ShareArray.Instance.ArrayList.Add(value);
或
var myarr = ShareArray.Instance.ArrayList;
这篇关于从不同的类了使用ArrayList中创建新的类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!