问题描述
我正在学习C#,我很新,所以请原谅我这个看似愚蠢的问题。我在Java有一些经验,我注意到,C#程序也需要一个 main()
方法在他们的主类。
I'm learning C# and I'm very new to it, so forgive me for the seemingly stupid question. I have some experience in Java, and I noticed that C# programs also need a main()
method in their main class.
如果我想创建一个不是主类的类,即我导入到主类中怎么办?
What if I want to create a class that isn't a main class, i.e. one that I import into a main class?
我试图这样做,当我编译(通过cmd使用 csc File.cs
)它会做的.exe没有 main()
方法。这是否意味着我错了,每个类需要一个 main()
方法,或者我编译错误?
I tried to do that, and when I compile (via cmd using csc File.cs
) the compiler says that the .exe that it will make has no main()
method. Does that mean that I was wrong, and every class needs a main()
method, or that I'm compiling it wrongly?
可能是代码中的问题(因为我依靠我对Java语法的了解),看起来像这样:
Maybe the problem's in the code (since I'm relying on my knowledge of Java syntax), which looks like this:
public class Class {
int stuff;
public Class(int stuff) {
this.stuff = stuff;
stuff();
}
public void method() {
stuff();
}
}
EDIT:恐怕这是非常误解。我不是问这个文件是否需要一个main方法,我想问我如何将这个类导入另一个类,因为我意识到,如果我这样做,我不能有一个主(正如我所说,我有一些Java经验),但每当我尝试编译没有一个编译器告诉我,我需要一个。
I'm afraid this is terribly misunderstood. I'm not asking if the file needs a main method, I'm asking how I can import this class into another class, because I realise that if I am to do this I can't have a main (as I said, I have some Java experience), but whenever I try to compile without one the compiler tells me that I need one.
推荐答案
as MSDN States
As MSDN States
在C#程序中只能有一个入口点。如果你有一个
比一个类有一个Main方法,你必须编译程序
用/ main编译器选项指定使用的Main方法作为
的入口点。 p>
There can only be one entry point in a C# program. If you have more than one class that has a Main method, you must compile your program with the /main compiler option to specify which Main method to use as the entry point.
只有一个类需要保留 Main
方法,该类充当应用程序的入口点。
Only one class need to keep the Main
method, the class which acts as entry point of the application.
主方法的签名是: static void Main [] args)
或 static void Main()
或 static int Main(string [] args)
或 static int Main()
The signature of the main method is : static void Main(string[] args)
or static void Main()
or static int Main(string[] args)
or static int Main()
查看此链接了解更多详情:
Check out this link for more details : Main() and Command-Line Arguments (C# Programming Guide
)
对于上述示例:
public class MyClassName // changed the class name, avoid using the reserved keyword :P
{
int stuff;
public MyClassName(int stuff) // is the constructor
{
this.stuff = stuff;
}
public void method()
{
stuff = 1;
}
}
如果您需要使用该类,一个静态类与main方法:
If you need to use that class, you can create a static class with main method:
class ProgramEntry
{
static void Main(string[] args)
{
MyClassName classInstance = new MyClassName(2);
classInstance.method();
}
}
这篇关于C#类无主方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!