CSharp-Learning/lessons/Lesson10/Program.cs

137 lines
3.9 KiB
C#
Raw Normal View History

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);
}
}
}