在C#中,除了类库(Class Library)之外,还有以下几种主要的项目类型:
控制台应用程序(Console Application):
- 输出类型:
OutputType=Exe - 特点:
- 在命令行窗口中运行
- 没有图形界面
- 适合后台处理、批处理等任务
- 示例:
csharpclass Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } }- 输出类型:
Windows窗体应用程序(Windows Forms Application):
- 输出类型:
OutputType=WinExe - 特点:
- 有图形用户界面
- 使用Windows Forms控件
- 适合桌面应用程序
- 示例:
csharppublic partial class Form1 : Form { public Form1() { InitializeComponent(); } }- 输出类型:
WPF应用程序(Windows Presentation Foundation):
- 输出类型:
OutputType=WinExe - 特点:
- 使用XAML设计界面
- 支持更丰富的UI效果
- 适合现代桌面应用
- 示例:
xaml<Window x:Class="WpfApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Title="MainWindow" Height="450" Width="800"> <Grid> <Button Content="Click Me"/> </Grid> </Window>- 输出类型:
Web应用程序(Web Application):
- ASP.NET Core Web App
- ASP.NET MVC
- 特点:
- 运行在Web服务器上
- 通过浏览器访问
- 支持HTTP请求处理
- 示例:
csharppublic class HomeController : Controller { public IActionResult Index() { return View(); } }Web API(Web API):
- 输出类型:
OutputType=Library - 特点:
- 提供HTTP API接口
- 返回JSON/XML数据
- 适合前后端分离项目
- 示例:
csharp[ApiController] [Route("[controller]")] public class WeatherController : ControllerBase { [HttpGet] public IActionResult Get() { return Ok(new { temperature = 25 }); } }- 输出类型:
Windows服务(Windows Service):
- 输出类型:
OutputType=WinExe - 特点:
- 在后台运行
- 没有用户界面
- 可以自动启动
- 示例:
csharppublic class MyService : ServiceBase { protected override void OnStart(string[] args) { // 服务启动时的代码 } }- 输出类型:
单元测试项目(Unit Test Project):
- 输出类型:
OutputType=Library - 特点:
- 用于编写测试代码
- 可以测试其他项目
- 支持自动化测试
- 示例:
csharp[TestClass] public class MyTests { [TestMethod] public void TestMethod1() { Assert.AreEqual(1, 1); } }- 输出类型:
移动应用程序(Mobile Application):
- Xamarin.Forms
- .NET MAUI
- 特点:
- 跨平台移动应用开发
- 支持iOS和Android
- 使用C#编写移动应用
- 示例:
csharppublic class App : Application { public App() { MainPage = new ContentPage { Content = new Label { Text = "Hello Mobile!" } }; } }通用Windows平台应用(UWP):
- 输出类型:
OutputType=WinExe - 特点:
- 运行在Windows 10/11上
- 支持现代Windows功能
- 可以从Windows商店分发
- 示例:
csharppublic sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } }- 输出类型:
Azure函数(Azure Functions):
- 输出类型:
OutputType=Library - 特点:
- 无服务器计算
- 按需执行
- 适合云服务
- 示例:
csharppublic static class Function1 { [FunctionName("Function1")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req) { return new OkObjectResult("Hello from Azure Function!"); } }- 输出类型: