简体   繁体   English

无法从静态方法调用函数

[英]Cannot call a function from a static method

Ok, this may sound like a very novice question.. i'm actually surprised i'm asking it. 好吧,这可能听起来像一个非常新手的问题..我真的很惊讶我问它。 I can't seem to remember how to call a function from inside static void Main() 我似乎无法记住如何从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()' 非静态字段,方法或属性'myNameSpace.Program.Run()'需要对象引用

You need to either make Run a static method or you need an object instance to call Run() of. 您需要使Run成为static方法,或者需要一个对象实例来调用Run() So your alternatives are: 所以你的选择是:

1.) Use an instance: 1.)使用实例:

new Program().Run();

2.) Make Run() static: 2.)使Run()静态:

static void Run()
{
   /..
}

Declare your Run() method as static too: Run()方法声明为静态:

static void Run()
{
   Console.WriteLine("Hello World!");
}

make方法static: static void Run()

Run()也必须是静态的,或者您需要像new Program().Run();一样创建对象的新实例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. 另一种方法是将Run()方法封装在嵌套类中并调用它。

        static void Main(string[] args)
    {
        new NestedClass().Run();
    }

    class NestedClass
    {
        public void Run()
        { 
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM