Cannot call a function from a static method
Ok, this may sound like a very novice question.. i'm act开发者_运维知识库ually surprised i'm asking it. I can't seem to remember how to call a function from inside static void Main()
namespace myNameSpace
{
class Program
{
static void Main()
{
Run(); // I receive an error here.
Console.ReadLine();
}
void Run()
{
Console.WriteLine("Hello World!");
}
}
}
error:
An object reference is required for the non-static field, method, or property 'myNameSpace.Program.Run()'
You need to either make Run
a static
method or you need an object instance to call Run()
of. So your alternatives are:
1.) Use an instance:
new Program().Run();
2.) Make Run()
static:
static void Run()
{
/..
}
Declare your Run()
method as static too:
static void Run()
{
Console.WriteLine("Hello World!");
}
Make method static: static void Run()
Run() must also be static or you need to create a new instance of the object like new Program().Run();
cause static function is not associate with an instance. while the none static function must have an instance.
So you have to create a new instance (each way you want) and then call the function.
The other way is to encapsulate your Run() method inside a nested class and invoke it.
static void Main(string[] args)
{
new NestedClass().Run();
}
class NestedClass
{
public void Run()
{
}
}
精彩评论