[C#]为什么当main方法是静态的时候所有其他方法都需要是静态的? [英] [C#] why when the main method is static all other methods needs to be static ?

查看:182
本文介绍了[C#]为什么当main方法是静态的时候所有其他方法都需要是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨人。我很困惑理解为什么当Main方法是静态的时候所有其他方法也必须是静态的?有人可以向我解释一下吗?



我的尝试:



在CodeProject.com中提出问题

Hi people. I have confusion understanding why when the Main method is static all the other methods must be static too ? Could someone explain that to me ?

What I have tried:

Asking a question here in CodeProject.com

推荐答案

它们不是!



main 方法必须是静态的,因为静态方法不需要类的实例才能被调用 - 所有非静态方法都需要先创建类的实例才能创建调用它们。

由于main方法是应用程序启动的地方,因此无法首先创建类实例(因为实例构造函数必须先运行才能调用 main 方法)。



一旦调用 main ,就可以创建实例,并在这些实例上调用非静态方法:



They aren't!

The main method must be static, because static methods do not need an instance of the class in order to be called - all non static methods require an instance of the class to be created before you can call them.
Since the main method is where your application starts, you can't create a class instance first (because the instance constructor would have to run before you could call the main method).

Once main has been called it can create instances, and call non-static methods on those instances:

static void main()
   {
   MyClass mc = new MyClass();
   ms.DoSomething();
   }


它们不需要全部是静态的。然而,静态方法没有对象(这个对象),而非静态方法有它。



你可以很容易地做到:

They don't need to be all static. Yet, the static method doesn't have an object (the this object) while the non-static methods have it.

You can very easily do:
class Program
{
  static void Main()
  {
    var program = new Program();
    program.DoSomething();
  }

  void DoSomething()
  {
    // here this will be available, and will be the program
    // variable created in the Main call. Note that you could
    // create more than one instance of the Program class.
  }
}


这篇关于[C#]为什么当main方法是静态的时候所有其他方法都需要是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆