VSCode中C#程序多入口点定义错误:求指定主入口的解决方案
Got it, I’ve hit this exact snag before when working with multiple classes that each have a Main method in VS Code! Unlike the full Visual Studio IDE where you can tweak project properties through a GUI, VS Code uses config files to handle this—but it’s still super easy to fix. Here are three reliable ways to resolve the error:
1. Set the entry point in launch.json (for debugging)
When you’re debugging your app, you can tell VS Code exactly which class’s Main method to use:
- Open the Run and Debug panel (press Ctrl+Shift+D, or click the bug icon on the left sidebar)
- If you don’t have a launch.json file yet, click "create a launch.json file" and select the .NET Core Console template
- Edit the existing configuration to add the
mainClassproperty, replacing the placeholder names with your actual namespace and class:
{ "version": "0.2.0", "configurations": [ { "name": ".NET Core Launch (console)", "type": "coreclr", "request": "launch", "preLaunchTask": "build", "program": "${workspaceFolder}/bin/Debug/net6.0/YourProjectName.dll", "args": [], "cwd": "${workspaceFolder}", "console": "internalConsole", "stopAtEntry": false, "mainClass": "YourNamespace.Program2" // This is where you specify your entry class } ] }
Save the file, and next time you debug, VS Code will use the Main method from Program2.
2. Set a default entry point in your .csproj file
If you want the same entry point to be used every time you build or run the app (not just when debugging), edit your project file:
- Open your
.csprojfile (it’s in the root of your workspace) - Add the
<StartupObject>element inside the<PropertyGroup>section, like this:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net6.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> <StartupObject>YourNamespace.Program2</StartupObject> <!-- Default entry point here --> </PropertyGroup> </Project>
Save the file, and now whenever you run dotnet build or dotnet run, it’ll automatically use the Main method from the class you specified.
3. Specify the entry point via command line
If you just want to test a different entry point one time without changing config files, use the --main flag when running with dotnet:
dotnet run --main YourNamespace.Program2
Or if you’re compiling first, you can pass the property directly to the build command:
dotnet build /property:StartupObject=YourNamespace.Program2
And if you don’t actually need two Main methods long-term, you can always rename one (like Program2Main) or comment it out to avoid the error entirely.
内容的提问来源于stack exchange,提问作者Bhawna Jain

