How to call a method from a different class
At the moment I have created a new method in a new class, an开发者_运维知识库d I am trying to call this method from my main class:
Program.cs:
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
testing();
Console.ReadLine();
}
}
}
and the method is in "Class1.cs":
namespace ConsoleApplication2
{
class Class1
{
public static void testing()
{
System.Console.WriteLine("It works!");
}
}
}
You need to specify the name of the class that the method is on. So:
Class1.testing();
Sometimes you might of course need to also worry about the namespace that Class1 is in. In this case both Class1 and Main are in the same namespace. If they hadn't been though then you'd have had to call it like:
ConsoleApplication2.DifferentNamespace.Class1.testing();
or with a using declaration at the top of program.cs:
using ConsoleApplication2.DifferentNamespace
You have made testing a static method, so you can call the method in this fashion
static void Main(string[] args)
{
Class1.testing();
Console.ReadLine();
}
Is this what you want ?
You are missing the class
declaration in order to use the static
method:
Class1.testing();
Class 1 has to be a public class and then you can call Class1.testing()
精彩评论