如何使用C#执行另一个.cs文件。

发布于 2025-02-06 14:31:54 字数 141 浏览 4 评论 0原文

我可以添加另一个.cs文件以外的program.cs并运行它吗? 我已经尝试多次运行其他.cs文件,但是每次是“ program.cs”,它将在终端执行并显示“ Hello World”输出。 除了“主要方法技巧”除外,是否有任何选择可以尽可能多地创建许多.cs文件?

Can i add another .cs file except Program.cs and run it?
I have tried multiple times to run other .cs files but every time it is "Program.cs" which is executing in terminal and shows "Hello World" output.
Except "Main method trick" is there any option to create many .cs files, as much as i can?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

知你几分 2025-02-13 14:31:54

主要方法是通过协议的.NET应用程序的切入点。如果没有严格的理解(和文档)对您的工作,请不要改变这种行为。

可能,您想在解决方案中使用每个项目中的主要方法创建一些项目。在这种情况下,选择要右运行的项目,请在解决方案资源管理器中单击它,然后选择“设置为启动项目” ”在此处输入图像说明”

Main method is an entry point for the .NET app by agreement. Don't change this behaviour without a strict understanding (and documentation) of what you're doing.

Probably, you would like to create a few projects in your solution, with the Main method in each. In that case select the project you want to run right clicking on it in the Solution Explorer and choosing "Set as Startup Project" enter image description here

对你的占有欲 2025-02-13 14:31:54

如果您要编译和运行单个文件,则可能仅将编译器设置为Compile program.cs。阅读本文,应该有所帮助:

编译/执行C c#源文件在命令提示符中

但是,如果您尝试从另一个文件执行代码,请尝试以下

程序。CS:

Console.WriteLine("Hello, World!");
SecondFile secondFile = new();
secondFile.MethodInFile2();

secondfile.cs:

class SecondFile {
    public void MethodInFile2() {
        Console.WriteLine("This is in the second file");
    }
}

If you are trying to compile and run an individual file, your compiler is likely set up to only compile Program.cs. Read this and it should help:

Compiling/Executing a C# Source File in Command Prompt

but if you are trying to execute code from another file, try the following

Program.cs:

Console.WriteLine("Hello, World!");
SecondFile secondFile = new();
secondFile.MethodInFile2();

SecondFile.cs:

class SecondFile {
    public void MethodInFile2() {
        Console.WriteLine("This is in the second file");
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文