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();
private void RemoveDuplicate(string sourceFilePath, string destinationFilePath)
{
var readLines = File.ReadAllLines(sourceFilePath, Encoding.Default);
File.WriteAllLines(destinationFilePath, readLines.Distinct().ToAr开发者_如何转开发ray(), Encoding.Default);
}
private void startremdup(object sender, EventArgs e)
{
RemoveDuplicate("C:\test.txt", "C:\test2.txt");
}
startremdup
is an instance method. 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.
Make both startremdup()
and RemoveDuplicate()
static.
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");
}
Make your methods static
as well.
startremdup and removeduplicate need to be declared as static if you are calling it from a static method (such as Main())
You can't call nonstatic methods from a static method unless you call them on an object reference. Check this out.
You need to either make both of those methods static, or create an instance of your Main
class and call the method from that.
Declare private static void startremdup(object sender, EventArgs e)
since static method can't call instance methods because they don't have this
.
精彩评论