[英]C# - How to call a method from static void main
I have some code in static void main, although I would like it to call the startremdup method (as it calls the RemoveDuplicate, with the appropriate parameters) from static void main, I have tried startremdup(); 我在静态void main中有一些代码,虽然我希望它从static void main调用startremdup方法(因为它调用RemoveDuplicate,带有适当的参数),我试过startremdup();
private void RemoveDuplicate(string sourceFilePath, string destinationFilePath)
{
var readLines = File.ReadAllLines(sourceFilePath, Encoding.Default);
File.WriteAllLines(destinationFilePath, readLines.Distinct().ToArray(), Encoding.Default);
}
private void startremdup(object sender, EventArgs e)
{
RemoveDuplicate("C:\test.txt", "C:\test2.txt");
}
startremdup
is an instance method. startremdup
是一个实例方法。 That means you need to call it on an instance of whatever class it's contained in. For example: 这意味着你需要在它包含的任何类的实例上调用它。例如:
Foo foo = new Foo();
foo.startremdup(null, EventArgs.Empty);
Personally it looks like it should be a static method to start with - and preferably one with a more sensible name - but that's why it's not working at the time. 就个人而言,它看起来应该是一个静态的方法 - 最好是一个名义更合理的方法 - 但这就是为什么它当时不起作用的原因。
If I were you, I'd actually put down your current task and pick up a good introductory C# book - learn the difference between static and instance members, etc. 如果我是你,我实际上会放下你当前的任务,拿起一本很好的入门C#书 - 了解静态和实例成员之间的区别等等。
Make both startremdup()
and RemoveDuplicate()
static. 使
startremdup()
和RemoveDuplicate()
静态的。
private static void RemoveDuplicate(string sourceFilePath, string destinationFilePath)
{
var readLines = File.ReadAllLines(sourceFilePath, Encoding.Default);
File.WriteAllLines(destinationFilePath, readLines.Distinct().ToArray(), Encoding.Default);
}
private static void startremdup(object sender, EventArgs e)
{
RemoveDuplicate("C:\test.txt", "C:\test2.txt");
}
使你的方法也是static
。
如果从静态方法(例如Main())调用startremdup和removeduplicate,则需要将其声明为static
您需要将这两个方法都设置为静态,或者创建Main
类的实例并从中调用该方法。
声明private static void startremdup(object sender, EventArgs e)
因为静态方法不能调用实例方法,因为它们没有this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.