C# class without main method

2019-04-21 14:47发布

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?

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?

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: 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.

标签: c# class main
9条回答
乱世女痞
2楼-- · 2019-04-21 15:12

static void main(string[] args) method in C# programs is the start point to execute. If you try to compile a single C# File, the compiler will find this method to start the execution. You don't need to create the method in a class you are using as a model, but you have to have this method on a Console Program, WinForms, etc...

查看更多
虎瘦雄心在
3楼-- · 2019-04-21 15:16

C# application must have at least one class with Main method, so that execution can begin from it. Application can have plenty of classes, but only one class with only one Main method is required.

C# library does not have to have a Main method.

查看更多
倾城 Initia
4楼-- · 2019-04-21 15:16

Try using /t:library switch with the compiler. By default it tries to make an .exe which, of course, needs an entry point (i.e. a main method). If you compile to a .dll you won't need that.

But as HighCore suggested, if you are learning, just use Visual Studio (download one of the free versions if you haven't already) and let it worry about the compiler flags.

查看更多
登录 后发表回答