在 C# 8.0 中,你可以编写各种程序,从简单的控制台应用到复杂的桌面、Web 或移动应用。下面,我将通过几个示例向你展示如何开始使用 C# 8.0 编写不同类型的程序。
1. 创建一个简单的控制台应用程序
步骤 1: 创建项目
在 Visual Studio 中,选择“创建新项目”。在项目模板中,选择“控制台应用 (.NET Core)”或“控制台应用 (.NET Framework)”,然后点击“下一步”。
步骤 2: 命名项目
给项目命名,例如 ConsoleAppDemo
,然后点击“创建”。
步骤 3: 编写代码
在 Program.cs
文件中,你可以编写以下代码:
using System;
namespace ConsoleAppDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.ReadLine(); // 等待用户输入,防止程序立即退出
}
}
}
步骤 4: 运行程序
按 F5 运行程序,你会在控制台窗口看到输出 "Hello, World!"。
2. 使用异步流和模式匹配(C# 8.0 新特性)
使用异步流(Asynchronous Streams)
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
var numbers = new[] { 1, 2, 3, 4, 5 };
await foreach (var number in GetNumbersAsync(numbers))
{
Console.WriteLine(number);
}
}
public static async IAsyncEnumerable<int> GetNumbersAsync(int[] numbers)
{
foreach (var number in numbers)
{
await Task.Delay(100); // 模拟异步操作,例如网络请求或文件IO操作
yield return number;
}
}
}
使用模式匹配(Pattern Matching)
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var list = new List<object> { 1, "Hello", 3.14 };
foreach (var item in list)
{
if (item is int i) // 使用 is 检查类型并同时赋值给变量 i
{
Console.WriteLine($"Integer: {i}");
}
else if (item is string s) // 使用 is 检查类型并同时赋值给变量 s
{
Console.WriteLine($"String: {s}");
}
else if (item is double d) // 使用 is 检查类型并同时赋值给变量 d
{
Console.WriteLine($"Double: {d}");
}
}
}
}
3. 创建一个 Windows Forms 应用程序(桌面应用)
步骤 1: 创建项目
在 Visual Studio 中,选择“创建新项目”。在项目模板中,选择“Windows Forms 应用”项目类型。命名项目,例如 WindowsFormsAppDemo
,然后点击“创建”。
步骤 2: 设计界面
使用设计视图添加控件,如按钮和文本框。双击按钮以添加点击事件处理程序。例如:
private void button1_Click(object sender, EventArgs e) {
textBox1.Text = "Hello, World!"; // 当按钮被点击时更改文本框的文本。
}
步骤 3: 运行程序并测试界面交互。
按 F5 运行程序,你会看到一个窗口,其中包含一个按钮和一个文本框。点击按钮后,文本框会显示 "Hello, World!"。
这些示例展示了 C# 8.0 在不同类型应用程序开发中的基本用法。你可以根据需要扩展和修改这些示例以适应更复杂的需求。