[英]How do i make instance for array of ToolStripMenuItem items?
In top of form1: 在form1顶部:
ToolStripMenuItem[] items;
In constructor: 在构造函数中:
for (int i = 0; i < items.Length; i++)
{
items[i] = new ToolStripMenuItem();
recentFilesToolStripMenuItem.DropDownItems.AddRange(items);
}
if (!File.Exists(@"e:\RecentFiles.txt"))
{
recentfiles = new StreamWriter(@"e:\RecentFiles.txt");
recentfiles.Close();
}
else
{
lines = File.ReadAllLines(@"e:\RecentFiles.txt");
}
Before it i used single item and i made one instance for it in the top of form1. 在此之前,我使用了单个项目,并在form1的顶部为其创建了一个实例。 But i want to add to the DropDownItems array of items. 但是我想添加到DropDownItems数组的项目。 And i don't how many items i want for it to be unlimited. 而且我不希望有多少项目是无限的。
Then i have this event: 然后我有这个事件:
private void recentFilesToolStripMenuItem_MouseEnter(object sender, EventArgs e)
{
for (int i = 0; i < lines.Length; i++)
{
items[i].Text = lines[i];
}
}
When i used a single item i just did in the MouseEnter event: 当我使用单个项目时,我只是在MouseEnter事件中这样做:
item.Text = "hello world";
But now i want to add the items from the text file it can be 1 items or 200 items the problem is that items are null in the constructor. 但是现在我想从文本文件中添加项目,它可以是1个项目或200个项目,问题是在构造函数中项目为null。
I did now in the constructor changed it to: 我现在在构造函数中将其更改为:
if (!File.Exists(@"e:\RecentFiles.txt"))
{
recentfiles = new StreamWriter(@"e:\RecentFiles.txt");
recentfiles.Close();
}
else
{
lines = File.ReadAllLines(@"e:\RecentFiles.txt");
items = new ToolStripMenuItem[lines.Length];
}
In this case lines.Length is 3. But now when i look on items i see 3 items that each one of them is null. 在这种情况下,lines.Length为3。但是现在当我查看项目时,我看到3个项目,其中每个项目都为空。 So i know how many items i need to instance but for some reason they are all null. 所以我知道我需要实例化多少个项目,但由于某种原因,它们都为空。
It seems, that your main problem is in the fact that you don't know in advance the length of items[]
; 看来,您的主要问题在于您不预先知道items[]
的长度 。 such problem is a good task for Linq , something like that: 对于Linq来说 ,这样的问题是一件好事,就像这样:
private ToolStripMenuItem[] items;
...
in the constructor: 在构造函数中:
items = File
.ReadLines(@"e:\RecentFiles.txt")
.Select(line => new ToolStripMenuItem() {
Text = line
})
.ToArray();
...
// if items are used in AddRange only
// you have no need neither of ToArray() nor in private field
recentFilesToolStripMenuItem.DropDownItems.AddRange(items);
in case you want, say, 10 first recent files only: 如果您只想要10个最近的文件:
items = File
.ReadLines(@"e:\RecentFiles.txt")
.Take(10)
.Select(line => new ToolStripMenuItem() {
Text = line
})
.ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.