我是 C# 的新手,以前只用 JavaScript 编写过程序,所以放轻松!
我编写了一个“应用程序启动器”程序,它逐行读取文本文件。每行只是一个程序的路径,例如 C:\Users\Jim\Desktop\Gravity.exe
到目前为止,我的程序可以成功读取每一行并生成链接列表。正如预期的那样,每个链接都显示为路径本身。
我遇到的问题是这些链接不起作用。但是,如果它们都被赋予相同的固定路径,它们将起作用。我希望每个链接都使用其 .Text 属性作为目标。(请参阅下面我的代码中的注释“有效”和“无效”)。我得到的唯一错误是“找不到指定的文件”。
我真的很感激这方面的任何帮助,因为我发现 C# 比 Javascript 更难!
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e) //on form load
{
int counter = 0;
string line;
string myfile = @"c:\users\matt\desktop\file.txt";
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(myfile);
while ((line = file.ReadLine()) != null)
{
//MessageBox.Show(line); //check whats on each line
LinkLabel mylinklabel = new LinkLabel(); //LinkLabel tells us the type of the object e.g. string mystring ="hello";
mylinklabel.Text = line;
this.Controls.Add(mylinklabel);
mylinklabel.Location = new Point(0, 30 + counter * 30);
mylinklabel.Click += new System.EventHandler(LinkClick);
counter++;
}
file.Close();
}
private void LinkClick(object sender, System.EventArgs e)
{
//Process.Start(this.Text); //doesn't work
Process.Start(@"C:\Users\Jim\Desktop\gravity.exe"); //works
}
}
更新:
谢谢你们的评论。我已将相关行更改为:
Process.Start(((LinkLabel)sender).Text);
......它确实有效。但也许我可以就这一行提出一个问题,因为我发现语法有点不寻常和令人困惑。
不是对象sender
的属性LinkLabel
吗?所以要引用它,我们不应该使用LinkLabel.sender
? (这将是更多的 JavaScript 风格!我不明白这个(LinkLabel)sender
符号)
我也不明白:
private void LinkClick(object sender, System.EventArgs e)
空间是什么意思?比如介于object
和sender
?还是在System.EventArgs
e 之间? LinkClick
是事件的名称,但是为什么我们这里有两个东西,用逗号分隔?
如您所知,我目前发现 C# 语法有点难!
先感谢您。