C# - 调用从静态的主要功能 [英] C# - Calling a function from static main

查看:160
本文介绍了C# - 调用从静态的主要功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题可能是很基本的,但我没有找到答案......

my question is probably very basic but I did not find an answer...

我写了一个函数(公共checkSomething,获取2串)Program.cs中
,当我试图从静态主
调用这个函数,我得到这个错误:

I wrote a function (public checkSomething that gets 2 strings) in program.cs when I tried to call this function from static main I got this error:

对象引用所需的非静态字段,方法或
属性'checkSomething(字符串,字符串)'。

"An object reference is required for a non-static field, method or property 'checkSomething(string,string)' ".

然而,当我改变了我的主要公共(而不是静态) - 没有错误。
为什么出现这种情况?什么是更好的 - 有一个静态主或不?为什么它甚至会事?

However,when I changed my main to Public (and not static)- there is no error. Why this happen? What is better - to have a Static main or not? Why would it even matter?

谢谢!

推荐答案

问题这里是不是静态的功能,但具体为什么 C#应用静态的。

The question here is not about static functions, but specifically why is main static in a C# application.

它与具有用于主应用程序只有一个线程做。这是通过使用 [STAThread] 主功能属性时定义。正在执行的线程进入主功能只有一次,因此不需要程序类的实例。

It has to do with having only one thread for the main application. This is defined when using the [STAThread] attribute on the main function. The executing thread enters the main function only once, and no instance of the Program class is required.

静态那么主要的功能可以初始化它正常运行时需要的任何类。这些都是经常的事像的形式,或工人类。

The static main function can then instantiate any classes it requires for normal operation. These are often things like forms, or worker classes.

该计划无论是在主线程进入一个消息循环来处理一个可见的形式,或者程序终止。

The program either enter a message loop in the main thread to process a visible form, or the program terminates.

当您删除主静态参考编译选项用于从启动该项目开关功能启动对象,类的一个实例之前创建主是调用。

When you remove the static reference for main the build options for the project switch from a startup function to a startup object, and an instance of the class is created before main is called.

这是个人喜好的问题,但要在启动过程中,曾经是只执行1个主主意。

It's a matter of personal preference, but keep in mind that only 1 main is ever executed during start up.

这篇关于C# - 调用从静态的主要功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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