Initial commit: C# 学习笔记和示例代码

- Lesson 01-10: C# 基础语法
- WebView2: 集成示例
- notes/: 详细笔记
This commit is contained in:
2026-07-01 16:31:35 +08:00
commit f604d53191
51 changed files with 2745 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+67
View File
@@ -0,0 +1,67 @@
using System;
namespace Lesson02
{
class Program
{
static void Main(string[] args)
{
// ========== 变量 ==========
int age = 25;
double height = 175.5;
string name = "无言势字幕";
char grade = 'A';
bool isActive = true;
Console.WriteLine("=== 变量 ===");
Console.WriteLine($"姓名: {name}");
Console.WriteLine($"年龄: {age}");
Console.WriteLine($"身高: {height}cm");
Console.WriteLine($"等级: {grade}");
Console.WriteLine($"状态: {isActive}");
// ========== var 自动推断 ==========
Console.WriteLine("\n=== var 自动推断 ===");
var message = "这是 string 类型";
var number = 42; // 推断为 int
Console.WriteLine($"message 是: {message.GetType()}");
Console.WriteLine($"number 是: {number.GetType()}");
// ========== 常量 ==========
Console.WriteLine("\n=== 常量 ===");
const int MAX_RETRY = 3;
const string VERSION = "v1.0";
Console.WriteLine($"最大重试次数: {MAX_RETRY}");
Console.WriteLine($"版本: {VERSION}");
// ========== 类型转换 ==========
Console.WriteLine("\n=== 类型转换 ===");
int i = 10;
double d = i; // 隐式转换
Console.WriteLine($"int -> double: {d}");
double d2 = 3.14;
int i2 = (int)d2; // 显式转换
Console.WriteLine($"double -> int: {i2}");
string s = i.ToString();
Console.WriteLine($"int -> string: {s}");
int i3 = int.Parse("123");
Console.WriteLine($"string \"123\" -> int: {i3}");
// ========== 输入练习 ==========
Console.WriteLine("\n=== 输入练习 ===");
Console.Write("请输入你的名字: ");
string inputName = Console.ReadLine();
Console.Write($"你好, {inputName}! ");
Console.Write("请输入年龄: ");
string ageInput = Console.ReadLine();
int userAge = int.Parse(ageInput);
Console.WriteLine($"你 {userAge} 岁了");
Console.ReadLine();
}
}
}
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+96
View File
@@ -0,0 +1,96 @@
using System;
namespace Lesson03
{
class Program
{
static void Main(string[] args)
{
// ========== if / else ==========
Console.WriteLine("=== if / else ===");
int score = 85;
if (score >= 90)
{
Console.WriteLine("优秀");
}
else if (score >= 60)
{
Console.WriteLine("及格");
}
else
{
Console.WriteLine("不及格");
}
// 三元运算符
string result = score >= 60 ? "及格" : "不及格";
Console.WriteLine($"三元运算: {result}");
// ========== switch ==========
Console.WriteLine("\n=== switch ===");
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("星期一");
break;
case 2:
Console.WriteLine("星期二");
break;
case 3:
Console.WriteLine("星期三");
break;
default:
Console.WriteLine("其他");
break;
}
// ========== for 循环 ==========
Console.WriteLine("\n=== for 循环 ===");
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"计数: {i}");
}
// ========== foreach ==========
Console.WriteLine("\n=== foreach 循环 ===");
string[] names = { "无言势", "VRChat", "字幕" };
foreach (string name in names)
{
Console.WriteLine(name);
}
// ========== while 循环 ==========
Console.WriteLine("\n=== while 循环 ===");
int count = 0;
while (count < 3)
{
Console.WriteLine($"while: {count}");
count++;
}
// ========== do while ==========
Console.WriteLine("\n=== do while ===");
int n = 0;
do
{
Console.WriteLine($"do while: {n}");
n++;
} while (n < 3);
// ========== break 和 continue ==========
Console.WriteLine("\n=== break 和 continue ===");
for (int i = 0; i < 10; i++)
{
if (i == 3) continue; // 跳过 3
if (i == 7) break; // 退出循环
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+119
View File
@@ -0,0 +1,119 @@
using System;
namespace Lesson04
{
class Program
{
static void Main(string[] args)
{
// ========== 方法调用 ==========
Console.WriteLine("=== 方法 ===");
SayHello("无言势");
int sum = Add(10, 20);
Console.WriteLine($"10 + 20 = {sum}");
// 带默认参数
Greet();
Greet("VRC");
// ========== 类和对象 ==========
Console.WriteLine("\n=== 类和对象 ===");
Person p1 = new Person("无言势", 25);
Person p2 = new Person("玩家A", 30);
p1.SayHi();
p2.SayHi();
// ========== 静态方法 ==========
Console.WriteLine("\n=== 静态方法 ===");
int result = MathHelper.Add(100, 200);
Console.WriteLine($"100 + 200 = {result}");
double pi = MathHelper.GetPI();
Console.WriteLine($"PI ≈ {pi}");
// ========== 面向对象练习 ==========
Console.WriteLine("\n=== 麦克风类 ===");
Microphone mic = new Microphone("USB麦克风", true);
mic.ToggleListening();
mic.ToggleListening();
Console.ReadLine();
}
// ========== 方法定义 ==========
static void SayHello(string name)
{
Console.WriteLine($"你好, {name}!");
}
static int Add(int a, int b)
{
return a + b;
}
static void Greet(string name = "World")
{
Console.WriteLine($"Hello, {name}");
}
}
// ========== 类定义 ==========
class Person
{
public string name;
public int age;
// 构造函数
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public void SayHi()
{
Console.WriteLine($"我是{name},今年{age}岁");
}
}
// 静态类
static class MathHelper
{
public static int Add(int a, int b)
{
return a + b;
}
public static double GetPI()
{
return 3.14159;
}
}
// 麦克风类 - 结合项目练习
class Microphone
{
private string name;
private bool isListening;
public Microphone(string name, bool isListening)
{
this.name = name;
this.isListening = isListening;
}
public void ToggleListening()
{
isListening = !isListening;
if (isListening)
{
Console.WriteLine($"[{name}] 开始监听...");
}
else
{
Console.WriteLine($"[{name}] 停止监听");
}
}
}
}
+27
View File
@@ -0,0 +1,27 @@
using System;
namespace Lesson05.Helpers
{
static class MathHelper
{
public static int Add(int a, int b)
{
return a + b;
}
public static int Multiply(int a, int b)
{
return a * b;
}
public static double Divide(int a, int b)
{
if (b == 0)
{
Console.WriteLine("除数不能为0!");
return 0;
}
return (double)a / b;
}
}
}
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+46
View File
@@ -0,0 +1,46 @@
using System;
namespace Lesson05.Models
{
class Person
{
// public: 任何地方都能访问
public string name;
// private: 只有本类内部能访问
private int age;
private string secret = "秘密信息";
// Property: 受保护的访问方式
public int Age
{
get { return age; }
set
{
// value 是关键字,表示赋值时的右值
if (value < 0) value = 0;
if (value > 150) value = 150;
age = value;
}
}
// 构造函数
public Person(string name, int age)
{
this.name = name;
this.Age = age; // 通过 Property 设置,自动限制范围
}
public void SayHi()
{
Console.WriteLine($"我是 {name},今年 {age} 岁");
Console.WriteLine($"我的秘密: {GetSecret()}"); // 本类内可以调用私有方法
}
// 私有方法:本类内部使用
private string GetSecret()
{
return secret;
}
}
}
+42
View File
@@ -0,0 +1,42 @@
using System;
using Lesson05.Models;
using Lesson05.Services;
using Lesson05.Helpers;
namespace Lesson05
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== 多文件项目演示 ===\n");
// 使用 Models 里的类
Person p = new Person("无言势", 25);
p.SayHi();
// 使用 Property
p.Age = -5; // 会自动限制范围
Console.WriteLine($"设置后年龄: {p.Age}");
p.Age = 200;
Console.WriteLine($"设置后年龄: {p.Age}");
// 使用 Services
AudioService service = new AudioService();
service.StartListening();
service.StopListening();
// 使用 Helpers
int sum = MathHelper.Add(100, 200);
Console.WriteLine($"\n100 + 200 = {sum}");
// 演示 private 无法访问
// p.secret = "xxx"; // 编译错误
// p.SetSecret("xxx"); // 编译错误
Console.WriteLine("\n=== 演示完成 ===");
Console.ReadLine();
}
}
}
+39
View File
@@ -0,0 +1,39 @@
using System;
namespace Lesson05.Services
{
class AudioService
{
private bool isListening;
private string deviceName;
public AudioService()
{
this.deviceName = "默认麦克风";
this.isListening = false;
}
public void StartListening()
{
if (!isListening)
{
isListening = true;
Console.WriteLine($"[{deviceName}] 开始监听...");
}
}
public void StopListening()
{
if (isListening)
{
isListening = false;
Console.WriteLine($"[{deviceName}] 停止监听");
}
}
public bool IsListening()
{
return isListening;
}
}
}
+25
View File
@@ -0,0 +1,25 @@
using System;
namespace Lesson06.Animals
{
class Animal
{
protected string name;
public Animal(string name)
{
this.name = name;
}
public void Eat()
{
Console.WriteLine($"{name} 在吃东西");
}
// virtual 允许子类重写
public virtual void Speak()
{
Console.WriteLine($"{name} 发出了声音");
}
}
}
+16
View File
@@ -0,0 +1,16 @@
using System;
namespace Lesson06.Animals
{
class Cat : Animal
{
public Cat(string name) : base(name)
{
}
public override void Speak()
{
Console.WriteLine($"{name} 喵喵喵~");
}
}
}
+27
View File
@@ -0,0 +1,27 @@
using System;
namespace Lesson06.Animals
{
class Dog : Animal
{
private string breed;
// base(name) 调用父类的构造函数
public Dog(string name, string breed) : base(name)
{
this.breed = breed;
}
public void Info()
{
Console.WriteLine($"名字: {name}, 品种: {breed}");
}
// 重写父类方法
public override void Speak()
{
base.Speak(); // 先调用父类方法
Console.WriteLine($"{name} 汪汪汪!");
}
}
}
+34
View File
@@ -0,0 +1,34 @@
using System;
namespace Lesson06.Devices
{
class Camera : IDevice
{
private string name;
public bool IsConnected { get; private set; }
public Camera(string name)
{
this.name = name;
this.IsConnected = false;
}
public void Connect()
{
if (!IsConnected)
{
IsConnected = true;
Console.WriteLine($"[{name}] 摄像头已连接");
}
}
public void Disconnect()
{
if (IsConnected)
{
IsConnected = false;
Console.WriteLine($"[{name}] 摄像头已断开");
}
}
}
}
+10
View File
@@ -0,0 +1,10 @@
namespace Lesson06.Devices
{
// 接口:定义契约
interface IDevice
{
void Connect();
void Disconnect();
bool IsConnected { get; }
}
}
+34
View File
@@ -0,0 +1,34 @@
using System;
namespace Lesson06.Devices
{
class Microphone : IDevice
{
private string name;
public bool IsConnected { get; private set; }
public Microphone(string name)
{
this.name = name;
this.IsConnected = false;
}
public void Connect()
{
if (!IsConnected)
{
IsConnected = true;
Console.WriteLine($"[{name}] 麦克风已连接");
}
}
public void Disconnect()
{
if (IsConnected)
{
IsConnected = false;
Console.WriteLine($"[{name}] 麦克风已断开");
}
}
}
}
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+55
View File
@@ -0,0 +1,55 @@
using System;
using Lesson06.Animals;
using Lesson06.Devices;
namespace Lesson06
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== 继承演示 ===\n");
// 继承:Dog 继承了 Animal
Dog dog = new Dog("旺财", "金毛");
dog.Eat();
dog.Speak();
dog.Info();
Console.WriteLine("\n=== 方法重写 ===\n");
// 多态:Cat 和 Dog 重写了 Speak
Animal cat = new Cat("小猫");
Animal dog2 = new Dog("二狗", "哈士奇");
cat.Speak();
dog2.Speak();
Console.WriteLine("\n=== 接口演示 ===\n");
// 使用接口
Microphone mic = new Microphone("USB麦克风");
Camera cam = new Camera("RTSP摄像头");
mic.Connect();
mic.Disconnect();
Console.WriteLine();
cam.Connect();
cam.Disconnect();
Console.WriteLine("\n=== 接口多态 ===\n");
// 接口类型可以指向任何实现它的类
IDevice device1 = new Microphone("设备A");
IDevice device2 = new Camera("设备B");
device1.Connect();
device2.Connect();
Console.WriteLine("\n=== 完成 ===");
Console.ReadLine();
}
}
}
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+107
View File
@@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
namespace Lesson07
{
class Program
{
static void Main(string[] args)
{
// ========== List<T> ==========
Console.WriteLine("=== List<T> 动态数组 ===\n");
List<string> transcriptHistory = new List<string>();
// 添加识别结果
transcriptHistory.Add("今天天气真不错");
transcriptHistory.Add("大家一起加油");
transcriptHistory.Add("这个功能很简单");
Console.WriteLine($"共有 {transcriptHistory.Count} 条记录:");
foreach (string text in transcriptHistory)
{
Console.WriteLine($" - {text}");
}
// 插入
transcriptHistory.Insert(1, "新插入的文字");
Console.WriteLine($"\n插入后共有 {transcriptHistory.Count} 条记录:");
foreach (string text in transcriptHistory)
{
Console.WriteLine($" - {text}");
}
// 删除
transcriptHistory.Remove("大家一起加油");
Console.WriteLine($"\n删除后共有 {transcriptHistory.Count} 条记录");
// 初始化器
List<string> fruits = new List<string>() { "苹果", "香蕉", "橙子" };
Console.WriteLine($"\n水果列表:{string.Join(", ", fruits)}");
// ========== Dictionary<K, V> ==========
Console.WriteLine("\n=== Dictionary<K, V> 键值对 ===\n");
// 设备配置
Dictionary<string, string> deviceConfig = new Dictionary<string, string>()
{
["name"] = "USB麦克风",
["sampleRate"] = "16000",
["channels"] = "1"
};
Console.WriteLine("设备配置:");
foreach (KeyValuePair<string, string> kv in deviceConfig)
{
Console.WriteLine($" {kv.Key}: {kv.Value}");
}
// 访问单个值
Console.WriteLine($"\n设备名称: {deviceConfig["name"]}");
// 安全访问
if (deviceConfig.TryGetValue("notExist", out string value))
{
Console.WriteLine($"找到: {value}");
}
else
{
Console.WriteLine("键不存在");
}
// 设置选项
Dictionary<string, bool> settings = new Dictionary<string, bool>()
{
["autoConnect"] = true,
["vad"] = true,
["debug"] = false
};
Console.WriteLine("\n设置选项:");
foreach (string key in settings.Keys)
{
string status = settings[key] ? "开启" : "关闭";
Console.WriteLine($" {key}: {status}");
}
// ========== 数字集合 ==========
Console.WriteLine("\n=== 数字 List 操作 ===\n");
List<int> scores = new List<int>() { 85, 92, 78, 95, 88 };
Console.WriteLine($"原始成绩:{string.Join(", ", scores)}");
scores.Sort();
Console.WriteLine($"排序后:{string.Join(", ", scores)}");
scores.Reverse();
Console.WriteLine($"反转后:{string.Join(", ", scores)}");
Console.WriteLine($"最高分:{scores[0]}");
Console.WriteLine($"包含 100? {scores.Contains(100)}");
Console.WriteLine($"包含 95? {scores.Contains(95)}");
Console.ReadLine();
}
}
}
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+187
View File
@@ -0,0 +1,187 @@
using System;
namespace Lesson08
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== 异常处理演示 ===\n");
// ========== 基本 try-catch ==========
Console.WriteLine("--- 基本 try-catch ---");
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[10]);
}
catch (Exception ex)
{
Console.WriteLine($"捕获异常: {ex.Message}");
}
// ========== 捕获特定异常 ==========
Console.WriteLine("\n--- 捕获特定异常 ---");
string[] inputs = { "123", "abc", "9999999999999" };
foreach (string input in inputs)
{
try
{
int num = int.Parse(input);
Console.WriteLine($"转换成功: {num}");
}
catch (FormatException)
{
Console.WriteLine($"\"{input}\" 格式错误,不是数字");
}
catch (OverflowException)
{
Console.WriteLine($"\"{input}\" 数字太大");
}
}
// ========== throw 抛出异常 ==========
Console.WriteLine("\n--- throw 抛出异常 ---");
try
{
SetAge(-5);
}
catch (ArgumentException ex)
{
Console.WriteLine($"捕获到: {ex.Message}");
}
try
{
SetAge(200);
}
catch (ArgumentException ex)
{
Console.WriteLine($"捕获到: {ex.Message}");
}
SetAge(25); // 正常
SetAge(0); // 正常
// ========== 实际项目场景 ==========
Console.WriteLine("\n--- 设备连接场景 ---");
MicrophoneDevice mic = new MicrophoneDevice("USB麦克风");
// 场景1:设备未连接
try
{
mic.StartListening();
}
catch (DeviceNotConnectedException ex)
{
Console.WriteLine($"错误: {ex.Message}");
Console.WriteLine("建议:请检查设备连接");
}
// 场景2:连接后正常操作
mic.Connect();
try
{
mic.StartListening();
Console.WriteLine("麦克风开始监听...");
mic.StopListening();
Console.WriteLine("麦克风停止监听...");
}
catch (DeviceNotConnectedException ex)
{
Console.WriteLine($"错误: {ex.Message}");
}
finally
{
mic.Disconnect();
Console.WriteLine("设备已断开");
}
// ========== finally 演示 ==========
Console.WriteLine("\n--- finally 执行时机 ---");
try
{
Console.WriteLine("try 块执行");
// int x = 1 / 0; // 解开这行会跳到 catch
}
catch
{
Console.WriteLine("catch 块执行");
}
finally
{
Console.WriteLine("finally 块总是执行");
}
Console.WriteLine("\n=== 演示完成 ===");
Console.ReadLine();
}
// ========== throw 示例 ==========
static void SetAge(int age)
{
if (age < 0 || age > 150)
{
throw new ArgumentException($"年龄必须在 0-150 之间,当前: {age}");
}
Console.WriteLine($"年龄设置为: {age}");
}
}
// ========== 自定义异常 ==========
class DeviceNotConnectedException : Exception
{
public DeviceNotConnectedException(string message) : base(message) { }
public DeviceNotConnectedException(string message, Exception inner) : base(message, inner) { }
}
// ========== 设备类 ==========
class MicrophoneDevice
{
private string name;
private bool isConnected;
private bool isListening;
public MicrophoneDevice(string name)
{
this.name = name;
this.isConnected = false;
this.isListening = false;
}
public void Connect()
{
isConnected = true;
Console.WriteLine($"[{name}] 设备已连接");
}
public void Disconnect()
{
isConnected = false;
Console.WriteLine($"[{name}] 设备已断开");
}
public void StartListening()
{
if (!isConnected)
{
throw new DeviceNotConnectedException($"{name} 未连接,无法开始监听");
}
if (isListening)
{
throw new InvalidOperationException($"{name} 已经在监听中");
}
isListening = true;
}
public void StopListening()
{
if (!isListening)
{
throw new InvalidOperationException($"{name} 没有在监听");
}
isListening = false;
}
}
}
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+103
View File
@@ -0,0 +1,103 @@
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Lesson09
{
class Program
{
static void Main(string[] args)
{
string basePath = Directory.GetCurrentDirectory();
string testFile = Path.Combine(basePath, "test.txt");
string configFile = Path.Combine(basePath, "config.json");
string logFile = Path.Combine(basePath, "app.log");
Console.WriteLine("=== 文件读写演示 ===\n");
// ========== 写入文本文件 ==========
Console.WriteLine("--- 写入文本文件 ---");
string content = "第一行:无言势字幕\n第二行:VRChat 语音识别工具";
File.WriteAllText(testFile, content);
Console.WriteLine($"已写入: {testFile}");
// ========== 读取文本文件 ==========
Console.WriteLine("\n--- 读取文本文件 ---");
string readContent = File.ReadAllText(testFile);
Console.WriteLine("文件内容:");
Console.WriteLine(readContent);
// ========== 按行读写 ==========
Console.WriteLine("\n--- 按行读取 ---");
string[] lines = File.ReadAllLines(testFile);
for (int i = 0; i < lines.Length; i++)
{
Console.WriteLine($"行 {i + 1}: {lines[i]}");
}
// ========== JSON 配置 ==========
Console.WriteLine("\n--- JSON 配置读写 ---");
// 创建设置对象
AppSettings settings = new AppSettings
{
Sensitivity = 75,
AutoConnect = true,
VadEnabled = true,
Language = "zh-CN"
};
// 序列化为 JSON
string json = JsonSerializer.Serialize(settings, new JsonSerializerOptions
{
WriteIndented = true // 格式化输出
});
File.WriteAllText(configFile, json);
Console.WriteLine("已保存配置: config.json");
Console.WriteLine(json);
// 反序列化
string loadedJson = File.ReadAllText(configFile);
AppSettings loadedSettings = JsonSerializer.Deserialize<AppSettings>(loadedJson);
Console.WriteLine("\n读取的配置:");
Console.WriteLine($" 灵敏度: {loadedSettings.Sensitivity}");
Console.WriteLine($" 自动连接: {loadedSettings.AutoConnect}");
Console.WriteLine($" VAD: {loadedSettings.VadEnabled}");
Console.WriteLine($" 语言: {loadedSettings.Language}");
// ========== 追加日志 ==========
Console.WriteLine("\n--- 追加日志 ---");
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string logEntry = $"[{timestamp}] 应用启动\n";
File.AppendAllText(logFile, logEntry);
Console.WriteLine($"已追加日志: {logFile}");
// ========== 文件操作 ==========
Console.WriteLine("\n--- 文件操作 ---");
Console.WriteLine($"文件是否存在: {File.Exists(testFile)}");
Console.WriteLine($"文件大小: {new FileInfo(testFile).Length} 字节");
Console.WriteLine($"完整路径: {Path.GetFullPath(testFile)}");
Console.WriteLine($"扩展名: {Path.GetExtension(testFile)}");
// ========== 清理 ==========
Console.WriteLine("\n--- 清理测试文件 ---");
if (File.Exists(testFile)) File.Delete(testFile);
if (File.Exists(configFile)) File.Delete(configFile);
if (File.Exists(logFile)) File.Delete(logFile);
Console.WriteLine("已删除测试文件");
Console.WriteLine("\n=== 演示完成 ===");
Console.ReadLine();
}
}
// ========== 配置类 ==========
class AppSettings
{
public int Sensitivity { get; set; } = 70;
public bool AutoConnect { get; set; } = true;
public bool VadEnabled { get; set; } = true;
public string Language { get; set; } = "zh-CN";
}
}
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+136
View File
@@ -0,0 +1,136 @@
using System;
namespace Lesson10
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== 委托和事件演示 ===\n");
// ========== 委托 ==========
Console.WriteLine("--- 委托 ---");
// Action: 无返回值的委托
Action<string> print = (msg) => Console.WriteLine($"打印: {msg}");
print("Hello World");
// Func: 有返回值的委托
Func<int, int, int> add = (a, b) => a + b;
Func<int, int, int> multiply = (a, b) => a * b;
Console.WriteLine($"add(3, 5) = {add(3, 5)}");
Console.WriteLine($"multiply(3, 5) = {multiply(3, 5)}");
// ========== 事件 ==========
Console.WriteLine("\n--- 事件 ---");
Microphone mic = new Microphone("USB麦克风");
// 订阅事件 - 收到文字时
mic.OnTranscriptReady += (text) =>
{
Console.WriteLine($"[UI更新] 显示文字: {text}");
};
// 订阅事件 - 开始监听
mic.OnListeningStarted += () =>
{
Console.WriteLine("[UI更新] 开始播放动画");
};
// 订阅事件 - 停止监听
mic.OnListeningStopped += () =>
{
Console.WriteLine("[UI更新] 停止动画");
};
// 订阅事件 - 错误处理
mic.OnError += (error) =>
{
Console.WriteLine($"[UI更新] 显示错误: {error}");
};
// ========== 模拟使用流程 ==========
Console.WriteLine("\n--- 模拟识别流程 ---");
// 正常流程
mic.StartListening();
mic.TranscriptDetected("今天天气真不错");
mic.TranscriptDetected("大家一起加油");
mic.StopListening();
Console.WriteLine();
// 模拟错误
mic.StartListening();
mic.SimulateError("设备断开连接");
mic.StopListening();
Console.WriteLine("\n=== 演示完成 ===");
Console.ReadLine();
}
}
// ========== 麦克风类(带事件) ==========
class Microphone
{
private string name;
private bool isListening;
// 事件声明
public event Action<string> OnTranscriptReady; // 识别出文字
public event Action OnListeningStarted; // 开始监听
public event Action OnListeningStopped; // 停止监听
public event Action<string> OnError; // 错误
public Microphone(string name)
{
this.name = name;
this.isListening = false;
}
public void StartListening()
{
if (isListening)
{
OnError?.Invoke("已经在监听中");
return;
}
isListening = true;
Console.WriteLine($"[{name}] 开始监听");
OnListeningStarted?.Invoke(); // 通知所有订阅者
}
public void StopListening()
{
if (!isListening)
{
return;
}
isListening = false;
Console.WriteLine($"[{name}] 停止监听");
OnListeningStopped?.Invoke(); // 通知所有订阅者
}
public void TranscriptDetected(string text)
{
if (!isListening)
{
return;
}
Console.WriteLine($"[{name}] 识别: {text}");
OnTranscriptReady?.Invoke(text); // 通知所有订阅者
}
// 模拟错误
public void SimulateError(string error)
{
Console.WriteLine($"[{name}] 错误: {error}");
OnError?.Invoke(error);
}
}
}
+24
View File
@@ -0,0 +1,24 @@
// Lesson 01: Hello World
// 目标:熟悉 C# 基本结构和输出
using System;
namespace CSharpLearning
{
class Lesson01_HelloWorld
{
static void Main(string[] args)
{
// 打印 hello world
Console.WriteLine("Hello, World!");
Console.WriteLine("你好,C#!");
// 打印带格式
string name = "无言势字幕";
Console.WriteLine($"项目名称: {name}");
// 等待输入(防止窗口关闭)
Console.ReadLine();
}
}
}
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+67
View File
@@ -0,0 +1,67 @@
using System;
namespace Lesson_One
{
class Program
{
static void Main(string[] args)
{
// ========== 变量 ==========
int age = 25;
double height = 175.5;
string name = "无言势字幕";
char grade = 'A';
bool isActive = true;
Console.WriteLine("=== 变量 ===");
Console.WriteLine($"姓名: {name}");
Console.WriteLine($"年龄: {age}");
Console.WriteLine($"身高: {height}cm");
Console.WriteLine($"等级: {grade}");
Console.WriteLine($"状态: {isActive}");
// ========== var 自动推断 ==========
Console.WriteLine("\n=== var 自动推断 ===");
var message = "这是 string 类型";
var number = 42; // 推断为 int
Console.WriteLine($"message 是: {message.GetType()}");
Console.WriteLine($"number 是: {number.GetType()}");
// ========== 常量 ==========
Console.WriteLine("\n=== 常量 ===");
const int MAX_RETRY = 3;
const string VERSION = "v1.0";
Console.WriteLine($"最大重试次数: {MAX_RETRY}");
Console.WriteLine($"版本: {VERSION}");
// ========== 类型转换 ==========
Console.WriteLine("\n=== 类型转换 ===");
int i = 10;
double d = i; // 隐式转换
Console.WriteLine($"int -> double: {d}");
double d2 = 3.14;
int i2 = (int)d2; // 显式转换
Console.WriteLine($"double -> int: {i2}");
string s = i.ToString();
Console.WriteLine($"int -> string: {s}");
int i3 = int.Parse("123");
Console.WriteLine($"string \"123\" -> int: {i3}");
// ========== 输入练习 ==========
Console.WriteLine("\n=== 输入练习 ===");
Console.Write("请输入你的名字: ");
string inputName = Console.ReadLine();
Console.Write($"你好, {inputName}! ");
Console.Write("请输入年龄: ");
string ageInput = Console.ReadLine();
int userAge = int.Parse(ageInput);
Console.WriteLine($"你 {userAge} 岁了");
Console.ReadLine();
}
}
}