C#/.NET 常用控件、属性、方法和语句大全(或许全)

C#/.NET 常用控件、属性、方法和语句大全

📊 一、Windows Forms 常用控件

1. 基础输入控件

控件名 图标 主要用途 常用属性
TextBox 📝 文本输入 Text, MaxLength, Multiline, PasswordChar, ReadOnly
Label 🏷️ 显示文本 Text, ForeColor, Font, TextAlign
Button 🔘 触发操作 Text, Enabled, Visible, BackColor, Image
CheckBox 多选项 Checked, Text, ThreeState
RadioButton 单选选项 Checked, Text, AutoCheck
ComboBox 🔽 下拉选择 Items, SelectedIndex, SelectedItem, DropDownStyle
ListBox 📋 列表选择 Items, SelectedIndex, SelectionMode, MultiColumn
DateTimePicker 📅 日期时间选择 Value, Format, MinDate, MaxDate
NumericUpDown 🔢 数字输入 Value, Minimum, Maximum, Increment

2. 容器和布局控件

csharp 复制代码
// Panel - 面板容器
Panel panel = new Panel();
panel.BorderStyle = BorderStyle.FixedSingle;  // 边框样式
panel.AutoScroll = true;                      // 自动滚动
panel.Dock = DockStyle.Fill;                  // 填充父容器

// GroupBox - 分组框
GroupBox groupBox = new GroupBox();
groupBox.Text = "用户信息";                   // 分组标题
groupBox.Controls.Add(textBox);              // 添加子控件

// TabControl - 选项卡
TabControl tabControl = new TabControl();
TabPage tabPage1 = new TabPage("基本信息");
TabPage tabPage2 = new TabPage("详细信息");
tabControl.TabPages.AddRange(new TabPage[] { tabPage1, tabPage2 });

// SplitContainer - 分割容器
SplitContainer splitContainer = new SplitContainer();
splitContainer.Orientation = Orientation.Horizontal;  // 水平分割
splitContainer.SplitterDistance = 200;               // 分割位置

// FlowLayoutPanel - 流式布局
FlowLayoutPanel flowPanel = new FlowLayoutPanel();
flowPanel.FlowDirection = FlowDirection.LeftToRight; // 从左到右排列
flowPanel.WrapContents = true;                      // 自动换行

// TableLayoutPanel - 表格布局
TableLayoutPanel tablePanel = new TableLayoutPanel();
tablePanel.ColumnCount = 3;                         // 3列
tablePanel.RowCount = 2;                           // 2行
tablePanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30));

3. 数据展示控件

csharp 复制代码
// DataGridView - 数据表格(最常用!)
DataGridView dataGridView = new DataGridView();
dataGridView.AutoGenerateColumns = false;           // 手动配置列
dataGridView.AllowUserToAddRows = false;           // 禁止添加行
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

// 添加列
dataGridView.Columns.Add("Name", "姓名");
dataGridView.Columns.Add("Age", "年龄");
dataGridView.Columns.Add("Gender", "性别");

// 绑定数据
List<Person> persons = GetPersons();
dataGridView.DataSource = persons;

// TreeView - 树形视图
TreeView treeView = new TreeView();
TreeNode root = new TreeNode("根节点");
TreeNode child1 = new TreeNode("子节点1");
root.Nodes.Add(child1);
treeView.Nodes.Add(root);
treeView.AfterSelect += TreeView_AfterSelect;      // 选中事件

// ListView - 列表视图
ListView listView = new ListView();
listView.View = View.Details;                      // 详细视图
listView.Columns.Add("文件名", 200);
listView.Columns.Add("大小", 100);
listView.Columns.Add("修改日期", 150);

// 添加项
ListViewItem item = new ListViewItem("文档.txt");
item.SubItems.Add("1.5 MB");
item.SubItems.Add("2024-01-15");
listView.Items.Add(item);

4. 菜单和工具栏

csharp 复制代码
// MenuStrip - 菜单栏
MenuStrip menuStrip = new MenuStrip();

// 文件菜单
ToolStripMenuItem fileMenu = new ToolStripMenuItem("文件(&F)");
ToolStripMenuItem newItem = new ToolStripMenuItem("新建(&N)");
newItem.ShortcutKeys = Keys.Control | Keys.N;      // 快捷键 Ctrl+N
newItem.Click += NewItem_Click;                    // 点击事件

ToolStripMenuItem exitItem = new ToolStripMenuItem("退出(&X)");
exitItem.Click += (s, e) => Application.Exit();   // 退出程序

fileMenu.DropDownItems.AddRange(new[] { newItem, exitItem });
menuStrip.Items.Add(fileMenu);

// ContextMenuStrip - 右键菜单
ContextMenuStrip contextMenu = new ContextMenuStrip();
contextMenu.Items.Add("复制", null, CopyItem_Click);
contextMenu.Items.Add("粘贴", null, PasteItem_Click);

// 关联到控件
textBox.ContextMenuStrip = contextMenu;

// ToolStrip - 工具栏
ToolStrip toolStrip = new ToolStrip();
toolStrip.Items.Add(new ToolStripButton("保存", null, Save_Click));
toolStrip.Items.Add(new ToolStripSeparator());     // 分隔符
toolStrip.Items.Add(new ToolStripButton("打印", null, Print_Click));

// StatusStrip - 状态栏
StatusStrip statusStrip = new StatusStrip();
ToolStripStatusLabel statusLabel = new ToolStripStatusLabel("就绪");
ToolStripProgressBar progressBar = new ToolStripProgressBar();
statusStrip.Items.AddRange(new ToolStripItem[] { statusLabel, progressBar });

5. 对话框控件

csharp 复制代码
// OpenFileDialog - 打开文件对话框
OpenFileDialog openDialog = new OpenFileDialog();
openDialog.Filter = "文本文件|*.txt|所有文件|*.*";
openDialog.Multiselect = true;                     // 允许多选
if (openDialog.ShowDialog() == DialogResult.OK)
{
    foreach (string fileName in openDialog.FileNames)
    {
        Console.WriteLine($"打开文件: {fileName}");
    }
}

// SaveFileDialog - 保存文件对话框
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "txt";                     // 默认扩展名
saveDialog.AddExtension = true;                    // 自动添加扩展名

// FolderBrowserDialog - 选择文件夹对话框
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.Description = "请选择保存的文件夹";
folderDialog.ShowNewFolderButton = true;           // 显示新建文件夹按钮

// ColorDialog - 颜色选择对话框
ColorDialog colorDialog = new ColorDialog();
colorDialog.Color = Color.Red;                     // 默认颜色
colorDialog.AllowFullOpen = true;                  // 允许自定义颜色

// FontDialog - 字体选择对话框
FontDialog fontDialog = new FontDialog();
fontDialog.ShowColor = true;                       // 显示颜色选项
fontDialog.FontMustExist = true;                   // 字体必须存在

// MessageBox - 消息框(最常用!)
// 显示信息
MessageBox.Show("操作成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

// 确认对话框
DialogResult result = MessageBox.Show("确定要删除吗?", "警告", 
    MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes)
{
    // 执行删除
}

6. 其他实用控件

csharp 复制代码
// PictureBox - 图片显示
PictureBox pictureBox = new PictureBox();
pictureBox.Image = Image.FromFile("image.jpg");
pictureBox.SizeMode = PictureBoxSizeMode.Zoom;      // 缩放模式

// ProgressBar - 进度条
ProgressBar progressBar = new ProgressBar();
progressBar.Minimum = 0;                           // 最小值
progressBar.Maximum = 100;                         // 最大值
progressBar.Value = 50;                            // 当前值
progressBar.Style = ProgressBarStyle.Marquee;      // 滚动样式

// Timer - 定时器(非可视化控件)
Timer timer = new Timer();
timer.Interval = 1000;                             // 1000毫秒=1秒
timer.Tick += Timer_Tick;                          // 定时事件
timer.Start();                                     // 启动定时器

// WebBrowser - 网页浏览器(已过时,推荐用WebView2)
WebBrowser webBrowser = new WebBrowser();
webBrowser.Navigate("https://www.example.com");    // 导航到网址
webBrowser.DocumentCompleted += WebBrowser_DocumentCompleted;

🔧 二、WPF 常用控件(对比 WinForms)

1. WPF 基础控件

xml 复制代码
<!-- TextBox - 文本框 -->
<TextBox x:Name="txtName" Text="请输入姓名" 
         Width="200" Height="30" 
         MaxLength="50" 
         TextChanged="TxtName_TextChanged"/>

<!-- Button - 按钮 -->
<Button Content="确定" 
        Width="80" Height="30"
        Click="BtnOK_Click"
        IsEnabled="{Binding CanSave}">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="Background" Value="LightBlue"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="Blue"/>
                    <Setter Property="Foreground" Value="White"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

<!-- ComboBox - 下拉框 -->
<ComboBox ItemsSource="{Binding Departments}"
          SelectedItem="{Binding SelectedDepartment}"
          DisplayMemberPath="Name"
          SelectedValuePath="Id">
</ComboBox>

<!-- DataGrid - 数据表格(比WinForms的DataGridView更强大) -->
<DataGrid x:Name="dataGrid" 
          ItemsSource="{Binding Persons}"
          AutoGenerateColumns="False"
          CanUserAddRows="False"
          SelectionMode="Single">
    <DataGrid.Columns>
        <DataGridTextColumn Header="姓名" Binding="{Binding Name}" Width="100"/>
        <DataGridTextColumn Header="年龄" Binding="{Binding Age}" Width="80"/>
        <DataGridCheckBoxColumn Header="已婚" Binding="{Binding IsMarried}" Width="60"/>
        <DataGridTemplateColumn Header="操作" Width="100">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Content="编辑" Click="EditButton_Click"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

<!-- ListView - 列表视图 -->
<ListView ItemsSource="{Binding Products}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="产品名" DisplayMemberBinding="{Binding ProductName}" Width="150"/>
            <GridViewColumn Header="价格" DisplayMemberBinding="{Binding Price, StringFormat=C}" Width="100"/>
        </GridView>
    </ListView.View>
</ListView>

2. WPF 布局控件

xml 复制代码
<!-- Grid - 网格布局(最常用) -->
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>    <!-- 自动高度 -->
        <RowDefinition Height="*"/>       <!-- 剩余空间 -->
        <RowDefinition Height="50"/>      <!-- 固定高度 -->
    </Grid.RowDefinitions>
    
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    
    <Label Grid.Row="0" Grid.Column="0" Content="用户名:"/>
    <TextBox Grid.Row="0" Grid.Column="1" x:Name="txtUsername"/>
    
    <DataGrid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"/>
    
    <StackPanel Grid.Row="2" Grid.ColumnSpan="2" Orientation="Horizontal" HorizontalAlignment="Right">
        <Button Content="保存" Margin="5"/>
        <Button Content="取消" Margin="5"/>
    </StackPanel>
</Grid>

<!-- StackPanel - 堆栈布局 -->
<StackPanel Orientation="Vertical" Margin="10">
    <Label Content="基本信息"/>
    <TextBox Margin="0,5"/>
    <TextBox Margin="0,5"/>
    <CheckBox Content="记住密码" Margin="0,5"/>
    <Button Content="登录" Margin="0,10"/>
</StackPanel>

<!-- DockPanel - 停靠布局 -->
<DockPanel LastChildFill="True">
    <Menu DockPanel.Dock="Top">
        <MenuItem Header="文件"/>
        <MenuItem Header="编辑"/>
    </Menu>
    
    <StatusBar DockPanel.Dock="Bottom">
        <StatusBarItem Content="就绪"/>
    </StatusBar>
    
    <TextBox Text="主要内容区域"/>
</DockPanel>

<!-- WrapPanel - 自动换行布局 -->
<WrapPanel>
    <Button Content="按钮1" Width="80" Height="30" Margin="5"/>
    <Button Content="按钮2" Width="80" Height="30" Margin="5"/>
    <!-- 超出宽度会自动换行 -->
</WrapPanel>

📖 三、C# 常用属性和方法

1. 字符串处理(最常用!)

csharp 复制代码
string text = " Hello World! ";

// 基本操作
int length = text.Length;                      // 长度:15
char firstChar = text[0];                      // 索引:' '
bool isEmpty = string.IsNullOrEmpty(text);     // 是否为空或null:false
bool isWhiteSpace = string.IsNullOrWhiteSpace(text); // 是否空白:false

// 修改字符串
string trimmed = text.Trim();                  // 去除首尾空格:"Hello World!"
string upper = text.ToUpper();                 // 转大写:" HELLO WORLD! "
string lower = text.ToLower();                 // 转小写:" hello world! "
string replaced = text.Replace("World", "C#"); // 替换:" Hello C#! "
string substring = text.Substring(1, 5);       // 子串:"Hello"

// 分割和连接
string csv = "Apple,Orange,Banana";
string[] fruits = csv.Split(',');              // 分割:["Apple", "Orange", "Banana"]
string joined = string.Join(" - ", fruits);    // 连接:"Apple - Orange - Banana"

// 查找和比较
bool startsWith = text.StartsWith("Hello");    // 是否以...开头:false(有空格)
bool endsWith = text.EndsWith("!");            // 是否以...结尾:true
bool contains = text.Contains("World");        // 是否包含:true
int index = text.IndexOf("World");             // 查找位置:7
int lastIndex = text.LastIndexOf("l");         // 最后出现位置:10

// 格式化
string formatted = string.Format("姓名:{0},年龄:{1}", "张三", 25);
string interpolated = $"姓名:{"张三"},年龄:{25}";  // C# 6.0+ 字符串插值
string padLeft = "123".PadLeft(5, '0');        // 左侧填充:"00123"
string padRight = "123".PadRight(5, '0');      // 右侧填充:"12300"

2. 数组和集合操作

csharp 复制代码
// 数组
int[] numbers = new int[5];                     // 声明数组
int[] numbers2 = { 1, 2, 3, 4, 5 };            // 初始化
Array.Sort(numbers);                           // 排序
Array.Reverse(numbers);                        // 反转
Array.Resize(ref numbers, 10);                 // 调整大小

// List<T> - 最常用的集合
List<string> names = new List<string>();
names.Add("张三");                              // 添加元素
names.AddRange(new[] { "李四", "王五" });       // 添加多个
names.Remove("张三");                           // 删除元素
names.RemoveAt(0);                             // 删除指定位置
names.Sort();                                  // 排序
names.Reverse();                               // 反转
bool exists = names.Contains("李四");           // 是否包含
int count = names.Count;                       // 元素数量
names.Clear();                                 // 清空

// Dictionary<K,V> - 键值对集合
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("张三", 90);
scores["李四"] = 85;                           // 添加或修改
int score = scores["张三"];                     // 获取值
bool hasKey = scores.ContainsKey("王五");       // 是否包含键
scores.Remove("张三");                          // 删除

// LINQ查询(非常重要!)
var query = from n in names
            where n.Length > 2
            orderby n descending
            select n.ToUpper();

// 方法语法(更常用)
var result = names
    .Where(n => n.Length > 2)
    .OrderByDescending(n => n)
    .Select(n => n.ToUpper())
    .ToList();

// 常用LINQ方法
var first = names.First();                     // 第一个元素
var firstOrDefault = names.FirstOrDefault();   // 第一个或默认值
var last = names.Last();                       // 最后一个元素
var any = names.Any();                         // 是否有元素
var all = names.All(n => n.Length > 1);        // 是否所有元素满足条件
var max = numbers.Max();                       // 最大值
var min = numbers.Min();                       // 最小值
var average = numbers.Average();               // 平均值
var sum = numbers.Sum();                       // 求和

3. 日期时间处理

csharp 复制代码
DateTime now = DateTime.Now;                    // 当前时间
DateTime today = DateTime.Today;               // 今天日期
DateTime utcNow = DateTime.UtcNow;             // UTC时间

// 创建特定日期
DateTime date1 = new DateTime(2024, 1, 15);    // 2024年1月15日
DateTime date2 = new DateTime(2024, 1, 15, 14, 30, 0); // 包含时间

// 日期运算
DateTime tomorrow = now.AddDays(1);            // 加1天
DateTime yesterday = now.AddDays(-1);          // 减1天
DateTime nextMonth = now.AddMonths(1);         // 加1个月
DateTime nextYear = now.AddYears(1);           // 加1年
TimeSpan diff = date2 - date1;                 // 时间差

// 日期部分
int year = now.Year;                           // 年:2024
int month = now.Month;                         // 月:1
int day = now.Day;                             // 日:15
int hour = now.Hour;                           // 时:14
int minute = now.Minute;                       // 分:30
DayOfWeek dayOfWeek = now.DayOfWeek;           // 星期:Monday

// 格式化
string shortDate = now.ToShortDateString();    // "2024/1/15"
string longDate = now.ToLongDateString();      // "2024年1月15日"
string shortTime = now.ToShortTimeString();    // "14:30"
string longTime = now.ToLongTimeString();      // "14:30:00"
string custom = now.ToString("yyyy-MM-dd HH:mm:ss"); // "2024-01-15 14:30:00"

// 解析
DateTime parsed = DateTime.Parse("2024-01-15");
DateTime.TryParse("2024-01-15", out DateTime result); // 安全解析

4. 文件操作

csharp 复制代码
// 文件信息
string path = @"C:\test\file.txt";
bool exists = File.Exists(path);               // 文件是否存在
DateTime created = File.GetCreationTime(path); // 创建时间
DateTime modified = File.GetLastWriteTime(path); // 修改时间
long size = new FileInfo(path).Length;         // 文件大小(字节)

// 读取文件
string content = File.ReadAllText(path);       // 读取所有文本
string[] lines = File.ReadAllLines(path);      // 按行读取
byte[] bytes = File.ReadAllBytes(path);        // 读取字节

// 写入文件
File.WriteAllText(path, "Hello World");        // 写入文本(覆盖)
File.AppendAllText(path, "\nNew Line");        // 追加文本
File.WriteAllLines(path, new[] { "Line1", "Line2" }); // 写入多行

// 文件操作
File.Copy(sourcePath, destPath);               // 复制文件
File.Move(sourcePath, destPath);               // 移动/重命名
File.Delete(path);                             // 删除文件

// 目录操作
string dirPath = @"C:\test";
Directory.CreateDirectory(dirPath);            // 创建目录
string[] files = Directory.GetFiles(dirPath);  // 获取所有文件
string[] directories = Directory.GetDirectories(dirPath); // 获取子目录
Directory.Delete(dirPath, true);               // 删除目录(递归)

// 路径操作
string fileName = Path.GetFileName(path);      // "file.txt"
string extension = Path.GetExtension(path);    // ".txt"
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(path); // "file"
string directoryName = Path.GetDirectoryName(path); // "C:\test"
string combined = Path.Combine(@"C:\test", "file.txt"); // 合并路径

// 流操作(大文件时使用)
using (FileStream fs = new FileStream(path, FileMode.Open))
using (StreamReader reader = new StreamReader(fs))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

🔑 四、C# 常用语句和语法

1. 控制流程语句

csharp 复制代码
// if-else 语句
int score = 85;
if (score >= 90)
{
    Console.WriteLine("优秀");
}
else if (score >= 80)
{
    Console.WriteLine("良好");
}
else if (score >= 60)
{
    Console.WriteLine("及格");
}
else
{
    Console.WriteLine("不及格");
}

// 三元运算符(简化if-else)
string grade = score >= 60 ? "及格" : "不及格";

// switch 语句
DayOfWeek today = DateTime.Today.DayOfWeek;
switch (today)
{
    case DayOfWeek.Monday:
        Console.WriteLine("星期一");
        break;
    case DayOfWeek.Tuesday:
        Console.WriteLine("星期二");
        break;
    case DayOfWeek.Wednesday:
    case DayOfWeek.Thursday:  // 多个case合并
        Console.WriteLine("周中");
        break;
    case DayOfWeek.Friday:
        Console.WriteLine("星期五");
        break;
    default:
        Console.WriteLine("周末");
        break;
}

// C# 8.0+ 的switch表达式(更简洁)
string dayType = today switch
{
    DayOfWeek.Monday or DayOfWeek.Tuesday or DayOfWeek.Wednesday 
        or DayOfWeek.Thursday or DayOfWeek.Friday => "工作日",
    _ => "周末"
};

2. 循环语句

csharp 复制代码
// for 循环
for (int i = 0; i < 10; i++)
{
    Console.WriteLine(i);
    if (i == 5)
        break;      // 跳出循环
}

// foreach 循环(最常用!)
List<string> names = new List<string> { "张三", "李四", "王五" };
foreach (string name in names)
{
    Console.WriteLine(name);
}

// while 循环
int count = 0;
while (count < 5)
{
    Console.WriteLine(count);
    count++;
}

// do-while 循环(至少执行一次)
int number;
do
{
    Console.Write("请输入正数:");
    number = int.Parse(Console.ReadLine());
} while (number <= 0);

3. 异常处理

csharp 复制代码
try
{
    // 可能出错的代码
    int result = 10 / int.Parse("0");
}
catch (DivideByZeroException ex)
{
    // 处理除以零异常
    Console.WriteLine("除数不能为零:" + ex.Message);
}
catch (FormatException ex)
{
    // 处理格式异常
    Console.WriteLine("输入格式错误:" + ex.Message);
}
catch (Exception ex)
{
    // 处理其他所有异常
    Console.WriteLine("发生错误:" + ex.Message);
    // 记录日志
    LogError(ex);
}
finally
{
    // 无论是否发生异常都会执行
    Console.WriteLine("清理资源...");
}

// throw 抛出异常
void ValidateAge(int age)
{
    if (age < 0 || age > 150)
        throw new ArgumentException("年龄必须在0-150之间");
}

// C# 6.0+ 异常过滤器
try
{
    // ...
}
catch (Exception ex) when (ex.Message.Contains("网络"))
{
    Console.WriteLine("网络错误:" + ex.Message);
}

4. 委托和事件

csharp 复制代码
// 定义委托
public delegate void MessageHandler(string message);

// 使用委托
MessageHandler handler = ShowMessage;
handler += LogMessage;  // 多播委托
handler("Hello");

void ShowMessage(string msg) => Console.WriteLine(msg);
void LogMessage(string msg) => Console.WriteLine($"[LOG] {msg}");

// Action(无返回值委托)
Action<string> action = msg => Console.WriteLine(msg);
action("Hello Action");

// Func(有返回值委托)
Func<int, int, int> add = (a, b) => a + b;
int sum = add(10, 20);

// 事件
public class Button
{
    public event EventHandler Clicked;
    
    public void Click()
    {
        Clicked?.Invoke(this, EventArgs.Empty);  // 触发事件
    }
}

// 订阅事件
Button btn = new Button();
btn.Clicked += (sender, e) => Console.WriteLine("按钮被点击");
btn.Click();

5. 异步编程(async/await)

csharp 复制代码
// 异步方法
public async Task<string> DownloadDataAsync(string url)
{
    using (HttpClient client = new HttpClient())
    {
        Console.WriteLine("开始下载...");
        string result = await client.GetStringAsync(url);
        Console.WriteLine("下载完成");
        return result;
    }
}

// 调用异步方法
async void Button_Click(object sender, EventArgs e)
{
    try
    {
        string data = await DownloadDataAsync("https://api.example.com");
        textBox.Text = data;
    }
    catch (Exception ex)
    {
        MessageBox.Show("下载失败:" + ex.Message);
    }
}

// 并行执行多个任务
public async Task ProcessMultipleAsync()
{
    Task<string> task1 = DownloadDataAsync("url1");
    Task<string> task2 = DownloadDataAsync("url2");
    
    // 等待所有任务完成
    string[] results = await Task.WhenAll(task1, task2);
    
    // 等待任意一个任务完成
    Task<string> completedTask = await Task.WhenAny(task1, task2);
}

6. LINQ 查询表达式

csharp 复制代码
// 数据源
List<Person> people = new List<Person>
{
    new Person { Name = "张三", Age = 25, City = "北京" },
    new Person { Name = "李四", Age = 30, City = "上海" },
    new Person { Name = "王五", Age = 28, City = "北京" },
    new Person { Name = "赵六", Age = 35, City = "广州" }
};

// 查询表达式(类似SQL)
var query = from p in people
            where p.Age > 25 && p.City == "北京"
            orderby p.Age descending
            select new { p.Name, p.Age };

// 方法链(更常用)
var result = people
    .Where(p => p.Age > 25 && p.City == "北京")
    .OrderByDescending(p => p.Age)
    .Select(p => new { p.Name, p.Age })
    .ToList();

// 分组查询
var groups = from p in people
             group p by p.City into g
             select new { City = g.Key, Count = g.Count(), AvgAge = g.Average(p => p.Age) };

// 连接查询
var orders = GetOrders();
var joined = from p in people
             join o in orders on p.Name equals o.CustomerName
             select new { p.Name, o.Product, o.Amount };

7. 面向对象编程(OOP)

csharp 复制代码
// 类定义
public class Person
{
    // 字段
    private string name;
    
    // 属性(封装字段)
    public string Name
    {
        get { return name; }
        set 
        { 
            if (string.IsNullOrWhiteSpace(value))
                throw new ArgumentException("姓名不能为空");
            name = value; 
        }
    }
    
    // 自动属性
    public int Age { get; set; }
    
    // 构造函数
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
    
    // 方法
    public virtual void Introduce()
    {
        Console.WriteLine($"我叫{Name},今年{Age}岁");
    }
}

// 继承
public class Student : Person
{
    public string StudentId { get; set; }
    
    public Student(string name, int age, string studentId) 
        : base(name, age)  // 调用基类构造函数
    {
        StudentId = studentId;
    }
    
    // 重写方法
    public override void Introduce()
    {
        base.Introduce();  // 调用基类方法
        Console.WriteLine($"学号:{StudentId}");
    }
}

// 接口
public interface IFlyable
{
    void Fly();
    int MaxAltitude { get; }
}

// 实现接口
public class Bird : IFlyable
{
    public void Fly()
    {
        Console.WriteLine("鸟儿在飞");
    }
    
    public int MaxAltitude => 1000;
}

// 抽象类
public abstract class Animal
{
    public abstract void MakeSound();  // 抽象方法
    
    public void Sleep()
    {
        Console.WriteLine("睡觉中...");
    }
}

// 使用
Person person = new Person("张三", 25);
person.Introduce();

Student student = new Student("李四", 20, "2024001");
student.Introduce();

IFlyable bird = new Bird();
bird.Fly();

8. 常用设计模式实现

csharp 复制代码
// 单例模式(保证一个类只有一个实例)
public class Singleton
{
    private static Singleton instance;
    private static readonly object lockObject = new object();
    
    private Singleton() { }  // 私有构造函数
    
    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (lockObject)  // 线程安全
                {
                    if (instance == null)
                        instance = new Singleton();
                }
            }
            return instance;
        }
    }
}

// 工厂模式
public interface IProduct { void Use(); }
public class ProductA : IProduct { public void Use() => Console.WriteLine("使用产品A"); }
public class ProductB : IProduct { public void Use() => Console.WriteLine("使用产品B"); }

public static class ProductFactory
{
    public static IProduct CreateProduct(string type)
    {
        return type switch
        {
            "A" => new ProductA(),
            "B" => new ProductB(),
            _ => throw new ArgumentException("不支持的产品类型")
        };
    }
}

// 观察者模式
public class Subject
{
    private List<IObserver> observers = new List<IObserver>();
    
    public void Attach(IObserver observer) => observers.Add(observer);
    public void Detach(IObserver observer) => observers.Remove(observer);
    
    public void Notify()
    {
        foreach (var observer in observers)
            observer.Update();
    }
}

public interface IObserver
{
    void Update();
}

🎯 五、实用代码片段

1. 常用扩展方法

csharp 复制代码
public static class Extensions
{
    // 字符串扩展:是否为数字
    public static bool IsNumeric(this string str)
    {
        return double.TryParse(str, out _);
    }
    
    // 字符串扩展:转换为安全的数据库字符串
    public static string ToSafeSql(this string str)
    {
        return str?.Replace("'", "''");
    }
    
    // DateTime扩展:是否为工作日
    public static bool IsWeekday(this DateTime date)
    {
        return date.DayOfWeek != DayOfWeek.Saturday && 
               date.DayOfWeek != DayOfWeek.Sunday;
    }
    
    // 集合扩展:批量添加
    public static void AddRange<T>(this ICollection<T> collection, params T[] items)
    {
        foreach (var item in items)
            collection.Add(item);
    }
    
    // 对象扩展:深度复制
    public static T DeepClone<T>(this T obj) where T : class
    {
        using (var ms = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Position = 0;
            return (T)formatter.Deserialize(ms);
        }
    }
}

2. 常用工具类

csharp 复制代码
public static class CommonHelper
{
    // 生成随机字符串
    public static string GenerateRandomString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        var random = new Random();
        return new string(Enumerable.Repeat(chars, length)
            .Select(s => s[random.Next(s.Length)]).ToArray());
    }
    
    // 计算MD5
    public static string CalculateMD5(string input)
    {
        using (var md5 = System.Security.Cryptography.MD5.Create())
        {
            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);
            return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
        }
    }
    
    // 对象转JSON
    public static string ToJson(object obj)
    {
        return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
    }
    
    // JSON转对象
    public static T FromJson<T>(string json)
    {
        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
    }
    
    // 验证邮箱格式
    public static bool IsValidEmail(string email)
    {
        try
        {
            var addr = new System.Net.Mail.MailAddress(email);
            return addr.Address == email;
        }
        catch
        {
            return false;
        }
    }
    
    // 获取程序运行目录
    public static string GetApplicationPath()
    {
        return AppDomain.CurrentDomain.BaseDirectory;
    }
}

📋 六、快速参考表

WinForms控件速查表

控件 用途 关键属性/方法
TextBox 文本输入 Text, ReadOnly, Multiline
Button 按钮 Text, Click事件
Label 标签 Text, TextAlign
ComboBox 下拉框 Items, SelectedItem
DataGridView 数据表格 DataSource, Columns, Rows
ListBox 列表框 Items, SelectedIndex
CheckBox 复选框 Checked, CheckState
RadioButton 单选框 Checked, GroupName
DateTimePicker 日期选择 Value, Format
PictureBox 图片显示 Image, SizeMode
ProgressBar 进度条 Value, Minimum, Maximum
MenuStrip 菜单 Items, 子菜单项
ToolStrip 工具栏 Items, 按钮、分隔符
StatusStrip 状态栏 Items, 状态标签
TabControl 选项卡 TabPages, SelectedTab
Panel 面板 BorderStyle, AutoScroll

C#常用语句速查表

语句 用途 示例
using 资源管理 using (var fs = new FileStream())
try-catch 异常处理 try { } catch (Exception ex) { }
if-else 条件判断 if (condition) { } else { }
switch 多分支 switch (value) { case 1: break; }
for 计数循环 for (int i=0; i<10; i++)
foreach 遍历集合 foreach (var item in collection)
while 条件循环 while (condition) { }
do-while 至少一次循环 do { } while (condition)
break 跳出循环 break;
continue 继续下次循环 continue;
return 返回值 return value;
throw 抛出异常 throw new Exception();
lock 线程同步 lock (obj) { }

💡 七、学习建议和最佳实践

给初学者的建议:

  1. 从WinForms开始:界面直观,容易上手
  2. 掌握常用控件:TextBox、Button、DataGridView 这几个最常用
  3. 理解事件驱动:Click、TextChanged、Load 等事件
  4. 练习数据绑定 :学会使用 DataSource 属性
  5. 学习异常处理:写出健壮的代码

最佳实践:

  1. 命名规范

    csharp 复制代码
    // 控件命名:类型前缀 + 描述
    txtUserName, btnSubmit, dgvProducts
    
    // 变量命名:camelCase
    string userName, int itemCount
    
    // 方法命名:PascalCase
    public void CalculateTotal()
  2. 资源管理

    csharp 复制代码
    // 使用using语句自动释放资源
    using (var connection = new SqlConnection(connStr))
    using (var command = new SqlCommand(sql, connection))
    {
        // ...
    }
  3. 错误处理

    csharp 复制代码
    // 使用try-catch处理预期错误
    try
    {
        // 业务代码
    }
    catch (SpecificException ex)
    {
        // 特定异常处理
        Logger.Log(ex);
    }
  4. 异步编程

    csharp 复制代码
    // UI操作使用异步避免卡顿
    private async void LoadDataButton_Click(object sender, EventArgs e)
    {
        btnLoad.Enabled = false;
        try
        {
            var data = await GetDataAsync();
            DisplayData(data);
        }
        finally
        {
            btnLoad.Enabled = true;
        }
    }
相关推荐
2501_944711432 小时前
A2UI : 以动态 UI 代替 LLM 文本输出的方案
开发语言·前端·ui
Antony_WU_SZ2 小时前
QT Qmake 方式在visual studio中的 环境配置
开发语言·qt
李慕婉学姐2 小时前
【开题答辩过程】以《基于Java的周边游优选推荐网站的设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·开发语言
Two_brushes.2 小时前
Cmake中寻库文件的路径
开发语言·c++·cmake
Larry_Yanan2 小时前
Qt安卓开发(三)双摄像头内嵌布局
android·开发语言·c++·qt·ui
wjs20242 小时前
Kotlin 条件控制
开发语言
我命由我123452 小时前
Kotlin 开发 - Kotlin Lambda 表达式返回值
android·java·开发语言·java-ee·kotlin·android studio·android-studio
雨中散步撒哈拉2 小时前
22、做中学 | 高一下期 | Golang反射
开发语言·golang·状态模式
a努力。2 小时前
中国电网Java面试被问:Dubbo的服务目录和路由链实现
java·开发语言·jvm·后端·面试·职场和发展·dubbo