学习目标

通过本章学习,您将掌握:

  1. 云原生开发

    • .NET 云原生应用开发
    • 容器化和微服务架构
    • Serverless 计算模式
    • 云平台集成和部署
  2. 边缘计算

    • .NET IoT 应用开发
    • 边缘设备编程
    • 实时数据处理
    • 设备管理和监控
  3. 现代化技术栈

    • .NET 8+ 新特性
    • Blazor 全栈开发
    • gRPC 和现代API设计
    • 性能优化技术
  4. 新兴应用领域

    • 区块链和Web3开发
    • 量子计算应用
    • AR/VR 应用开发
    • 跨平台移动开发

25.1 云原生开发

.NET 云原生应用架构

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using System;
using System.Threading.Tasks;

// 云原生应用启动配置
public class CloudNativeStartup
{
    private readonly IConfiguration _configuration;
    
    public CloudNativeStartup(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    
    public void ConfigureServices(IServiceCollection services)
    {
        // 健康检查
        services.AddHealthChecks()
            .AddCheck<DatabaseHealthCheck>("database")
            .AddCheck<RedisHealthCheck>("redis")
            .AddCheck<ExternalServiceHealthCheck>("external-api");
        
        // 配置管理
        services.Configure<CloudConfiguration>(_configuration.GetSection("Cloud"));
        
        // 分布式缓存
        services.AddStackExchangeRedisCache(options =>
        {
            options.Configuration = _configuration.GetConnectionString("Redis");
            options.InstanceName = "CloudNativeApp";
        });
        
        // 消息队列
        services.AddSingleton<IMessageBus, ServiceBusMessageBus>();
        
        // 监控和遥测
        services.AddApplicationInsightsTelemetry();
        services.AddOpenTelemetryTracing(builder =>
        {
            builder.AddAspNetCoreInstrumentation()
                   .AddHttpClientInstrumentation()
                   .AddSqlClientInstrumentation()
                   .AddJaegerExporter();
        });
        
        // 安全认证
        services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Authority = _configuration["Auth:Authority"];
                options.TokenValidationParameters.ValidateAudience = false;
            });
        
        // API版本控制
        services.AddApiVersioning(options =>
        {
            options.DefaultApiVersion = new ApiVersion(1, 0);
            options.AssumeDefaultVersionWhenUnspecified = true;
            options.ApiVersionReader = ApiVersionReader.Combine(
                new QueryStringApiVersionReader("version"),
                new HeaderApiVersionReader("X-Version")
            );
        });
        
        // 限流
        services.AddRateLimiter(options =>
        {
            options.AddFixedWindowLimiter("api", limiterOptions =>
            {
                limiterOptions.PermitLimit = 100;
                limiterOptions.Window = TimeSpan.FromMinutes(1);
            });
        });
        
        // 业务服务
        services.AddScoped<IUserService, UserService>();
        services.AddScoped<IOrderService, OrderService>();
        services.AddScoped<INotificationService, NotificationService>();
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }
        
        // 健康检查端点
        app.UseHealthChecks("/health", new HealthCheckOptions
        {
            ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
        });
        
        // 监控中间件
        app.UseMiddleware<RequestLoggingMiddleware>();
        app.UseMiddleware<PerformanceMiddleware>();
        
        // 安全中间件
        app.UseAuthentication();
        app.UseAuthorization();
        
        // 限流
        app.UseRateLimiter();
        
        // 路由
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHealthChecks("/health");
        });
    }
}

// 云配置
public class CloudConfiguration
{
    public string Environment { get; set; }
    public string Region { get; set; }
    public string SubscriptionId { get; set; }
    public string ResourceGroup { get; set; }
    public StorageConfiguration Storage { get; set; }
    public DatabaseConfiguration Database { get; set; }
    public MessagingConfiguration Messaging { get; set; }
}

public class StorageConfiguration
{
    public string ConnectionString { get; set; }
    public string ContainerName { get; set; }
    public bool UseAzureStorage { get; set; }
}

public class DatabaseConfiguration
{
    public string ConnectionString { get; set; }
    public bool UseCosmosDB { get; set; }
    public int MaxRetryAttempts { get; set; }
}

public class MessagingConfiguration
{
    public string ServiceBusConnectionString { get; set; }
    public string EventHubConnectionString { get; set; }
    public bool UseServiceBus { get; set; }
}

Serverless 函数开发

using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Net;
using System.Threading.Tasks;
using System.Text.Json;

// Azure Functions 示例
public class ServerlessFunctions
{
    private readonly ILogger _logger;
    private readonly IUserService _userService;
    private readonly INotificationService _notificationService;
    
    public ServerlessFunctions(ILoggerFactory loggerFactory, 
                              IUserService userService,
                              INotificationService notificationService)
    {
        _logger = loggerFactory.CreateLogger<ServerlessFunctions>();
        _userService = userService;
        _notificationService = notificationService;
    }
    
    // HTTP 触发器
    [Function("ProcessUserRegistration")]
    public async Task<HttpResponseData> ProcessUserRegistration(
        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req)
    {
        _logger.LogInformation("Processing user registration request.");
        
        try
        {
            var requestBody = await req.ReadAsStringAsync();
            var registrationData = JsonSerializer.Deserialize<UserRegistrationData>(requestBody);
            
            // 验证数据
            if (!IsValidRegistrationData(registrationData))
            {
                var badResponse = req.CreateResponse(HttpStatusCode.BadRequest);
                await badResponse.WriteStringAsync("Invalid registration data");
                return badResponse;
            }
            
            // 创建用户
            var user = await _userService.CreateUserAsync(registrationData);
            
            // 发送欢迎邮件
            await _notificationService.SendWelcomeEmailAsync(user.Email, user.Name);
            
            var response = req.CreateResponse(HttpStatusCode.OK);
            await response.WriteAsJsonAsync(new { UserId = user.Id, Message = "User registered successfully" });
            return response;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error processing user registration");
            var errorResponse = req.CreateResponse(HttpStatusCode.InternalServerError);
            await errorResponse.WriteStringAsync("Internal server error");
            return errorResponse;
        }
    }
    
    // 定时器触发器
    [Function("DailyReportGenerator")]
    public async Task GenerateDailyReport([TimerTrigger("0 0 8 * * *")] TimerInfo timer)
    {
        _logger.LogInformation($"Daily report generation started at: {DateTime.Now}");
        
        try
        {
            var reportData = await _userService.GetDailyStatisticsAsync();
            var report = new DailyReport
            {
                Date = DateTime.Today,
                NewUsers = reportData.NewUsers,
                ActiveUsers = reportData.ActiveUsers,
                TotalRevenue = reportData.TotalRevenue
            };
            
            // 生成报告
            var reportContent = GenerateReportContent(report);
            
            // 发送给管理员
            await _notificationService.SendDailyReportAsync(reportContent);
            
            _logger.LogInformation("Daily report generated and sent successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error generating daily report");
        }
    }
    
    // 队列触发器
    [Function("ProcessOrderQueue")]
    public async Task ProcessOrderQueue(
        [ServiceBusTrigger("orders", Connection = "ServiceBusConnection")] string orderMessage)
    {
        _logger.LogInformation($"Processing order: {orderMessage}");
        
        try
        {
            var order = JsonSerializer.Deserialize<Order>(orderMessage);
            
            // 处理订单
            await ProcessOrderAsync(order);
            
            // 发送确认邮件
            await _notificationService.SendOrderConfirmationAsync(order.CustomerEmail, order.Id);
            
            _logger.LogInformation($"Order {order.Id} processed successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"Error processing order: {orderMessage}");
            throw; // 重新抛出异常以触发重试机制
        }
    }
    
    // Blob 触发器
    [Function("ProcessUploadedFile")]
    public async Task ProcessUploadedFile(
        [BlobTrigger("uploads/{name}", Connection = "StorageConnection")] Stream blobStream,
        string name)
    {
        _logger.LogInformation($"Processing uploaded file: {name}");
        
        try
        {
            // 文件处理逻辑
            if (IsImageFile(name))
            {
                await ProcessImageAsync(blobStream, name);
            }
            else if (IsDocumentFile(name))
            {
                await ProcessDocumentAsync(blobStream, name);
            }
            
            _logger.LogInformation($"File {name} processed successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"Error processing file: {name}");
        }
    }
    
    private bool IsValidRegistrationData(UserRegistrationData data)
    {
        return !string.IsNullOrEmpty(data?.Email) && 
               !string.IsNullOrEmpty(data?.Name) && 
               !string.IsNullOrEmpty(data?.Password);
    }
    
    private string GenerateReportContent(DailyReport report)
    {
        return $"Daily Report for {report.Date:yyyy-MM-dd}\n" +
               $"New Users: {report.NewUsers}\n" +
               $"Active Users: {report.ActiveUsers}\n" +
               $"Total Revenue: ${report.TotalRevenue:F2}";
    }
    
    private async Task ProcessOrderAsync(Order order)
    {
        // 订单处理逻辑
        await Task.Delay(100); // 模拟处理时间
    }
    
    private bool IsImageFile(string fileName)
    {
        var imageExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
        return imageExtensions.Any(ext => fileName.EndsWith(ext, StringComparison.OrdinalIgnoreCase));
    }
    
    private bool IsDocumentFile(string fileName)
    {
        var docExtensions = new[] { ".pdf", ".doc", ".docx", ".txt" };
        return docExtensions.Any(ext => fileName.EndsWith(ext, StringComparison.OrdinalIgnoreCase));
    }
    
    private async Task ProcessImageAsync(Stream imageStream, string fileName)
    {
        // 图像处理逻辑
        await Task.Delay(200);
    }
    
    private async Task ProcessDocumentAsync(Stream documentStream, string fileName)
    {
        // 文档处理逻辑
        await Task.Delay(150);
    }
}

// 数据模型
public class UserRegistrationData
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string PhoneNumber { get; set; }
}

public class DailyReport
{
    public DateTime Date { get; set; }
    public int NewUsers { get; set; }
    public int ActiveUsers { get; set; }
    public decimal TotalRevenue { get; set; }
}

public class Order
{
    public string Id { get; set; }
    public string CustomerEmail { get; set; }
    public decimal Amount { get; set; }
    public DateTime OrderDate { get; set; }
    public List<OrderItem> Items { get; set; }
}

public class OrderItem
{
    public string ProductId { get; set; }
    public string ProductName { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
}

25.2 边缘计算

.NET IoT 应用开发

using System;
using System.Device.Gpio;
using System.Device.I2c;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;

// IoT 设备管理器
public class IoTDeviceManager : BackgroundService
{
    private readonly ILogger<IoTDeviceManager> _logger;
    private readonly IServiceProvider _serviceProvider;
    private readonly GpioController _gpioController;
    private readonly Dictionary<string, ISensor> _sensors;
    private readonly Dictionary<string, IActuator> _actuators;
    
    public IoTDeviceManager(ILogger<IoTDeviceManager> logger, IServiceProvider serviceProvider)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;
        _gpioController = new GpioController();
        _sensors = new Dictionary<string, ISensor>();
        _actuators = new Dictionary<string, IActuator>();
        
        InitializeDevices();
    }
    
    private void InitializeDevices()
    {
        // 初始化传感器
        _sensors["temperature"] = new TemperatureSensor(_gpioController, 18);
        _sensors["humidity"] = new HumiditySensor(_gpioController, 19);
        _sensors["motion"] = new MotionSensor(_gpioController, 20);
        _sensors["light"] = new LightSensor(_gpioController, 21);
        
        // 初始化执行器
        _actuators["led"] = new LedActuator(_gpioController, 22);
        _actuators["fan"] = new FanActuator(_gpioController, 23);
        _actuators["buzzer"] = new BuzzerActuator(_gpioController, 24);
        
        _logger.LogInformation("IoT devices initialized successfully");
    }
    
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("IoT Device Manager started");
        
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await CollectSensorDataAsync();
                await ProcessAutomationRulesAsync();
                await Task.Delay(5000, stoppingToken); // 每5秒执行一次
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in IoT device management loop");
            }
        }
    }
    
    private async Task CollectSensorDataAsync()
    {
        var sensorData = new Dictionary<string, object>();
        
        foreach (var sensor in _sensors)
        {
            try
            {
                var value = await sensor.Value.ReadAsync();
                sensorData[sensor.Key] = value;
                _logger.LogDebug($"Sensor {sensor.Key}: {value}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error reading sensor {sensor.Key}");
            }
        }
        
        // 发送数据到云端
        using var scope = _serviceProvider.CreateScope();
        var cloudService = scope.ServiceProvider.GetRequiredService<ICloudDataService>();
        await cloudService.SendSensorDataAsync(sensorData);
    }
    
    private async Task ProcessAutomationRulesAsync()
    {
        // 自动化规则处理
        var temperature = await _sensors["temperature"].ReadAsync();
        var humidity = await _sensors["humidity"].ReadAsync();
        var motion = await _sensors["motion"].ReadAsync();
        var light = await _sensors["light"].ReadAsync();
        
        // 温度控制
        if (temperature is double temp)
        {
            if (temp > 25.0)
            {
                await _actuators["fan"].ActivateAsync();
                _logger.LogInformation($"Fan activated due to high temperature: {temp}°C");
            }
            else if (temp < 20.0)
            {
                await _actuators["fan"].DeactivateAsync();
            }
        }
        
        // 运动检测照明
        if (motion is bool hasMotion && hasMotion)
        {
            if (light is double lightLevel && lightLevel < 50.0)
            {
                await _actuators["led"].ActivateAsync();
                _logger.LogInformation("LED activated due to motion detection in low light");
            }
        }
        
        // 湿度警报
        if (humidity is double hum && hum > 80.0)
        {
            await _actuators["buzzer"].ActivateAsync();
            await Task.Delay(1000);
            await _actuators["buzzer"].DeactivateAsync();
            _logger.LogWarning($"High humidity alert: {hum}%");
        }
    }
    
    public override void Dispose()
    {
        foreach (var sensor in _sensors.Values)
        {
            sensor.Dispose();
        }
        
        foreach (var actuator in _actuators.Values)
        {
            actuator.Dispose();
        }
        
        _gpioController?.Dispose();
        base.Dispose();
    }
}

// 传感器接口和实现
public interface ISensor : IDisposable
{
    Task<object> ReadAsync();
}

public class TemperatureSensor : ISensor
{
    private readonly GpioController _controller;
    private readonly int _pin;
    
    public TemperatureSensor(GpioController controller, int pin)
    {
        _controller = controller;
        _pin = pin;
        _controller.OpenPin(_pin, PinMode.Input);
    }
    
    public async Task<object> ReadAsync()
    {
        // 模拟温度读取(实际应用中需要根据具体传感器实现)
        await Task.Delay(10);
        var random = new Random();
        return 20.0 + random.NextDouble() * 15.0; // 20-35°C
    }
    
    public void Dispose()
    {
        _controller?.ClosePin(_pin);
    }
}

public class HumiditySensor : ISensor
{
    private readonly GpioController _controller;
    private readonly int _pin;
    
    public HumiditySensor(GpioController controller, int pin)
    {
        _controller = controller;
        _pin = pin;
        _controller.OpenPin(_pin, PinMode.Input);
    }
    
    public async Task<object> ReadAsync()
    {
        await Task.Delay(10);
        var random = new Random();
        return 30.0 + random.NextDouble() * 60.0; // 30-90%
    }
    
    public void Dispose()
    {
        _controller?.ClosePin(_pin);
    }
}

public class MotionSensor : ISensor
{
    private readonly GpioController _controller;
    private readonly int _pin;
    
    public MotionSensor(GpioController controller, int pin)
    {
        _controller = controller;
        _pin = pin;
        _controller.OpenPin(_pin, PinMode.Input);
    }
    
    public async Task<object> ReadAsync()
    {
        await Task.Delay(5);
        return _controller.Read(_pin) == PinValue.High;
    }
    
    public void Dispose()
    {
        _controller?.ClosePin(_pin);
    }
}

public class LightSensor : ISensor
{
    private readonly GpioController _controller;
    private readonly int _pin;
    
    public LightSensor(GpioController controller, int pin)
    {
        _controller = controller;
        _pin = pin;
        _controller.OpenPin(_pin, PinMode.Input);
    }
    
    public async Task<object> ReadAsync()
    {
        await Task.Delay(10);
        var random = new Random();
        return random.NextDouble() * 100.0; // 0-100 lux
    }
    
    public void Dispose()
    {
        _controller?.ClosePin(_pin);
    }
}

// 执行器接口和实现
public interface IActuator : IDisposable
{
    Task ActivateAsync();
    Task DeactivateAsync();
    bool IsActive { get; }
}

public class LedActuator : IActuator
{
    private readonly GpioController _controller;
    private readonly int _pin;
    private bool _isActive;
    
    public LedActuator(GpioController controller, int pin)
    {
        _controller = controller;
        _pin = pin;
        _controller.OpenPin(_pin, PinMode.Output);
        _controller.Write(_pin, PinValue.Low);
    }
    
    public bool IsActive => _isActive;
    
    public async Task ActivateAsync()
    {
        _controller.Write(_pin, PinValue.High);
        _isActive = true;
        await Task.CompletedTask;
    }
    
    public async Task DeactivateAsync()
    {
        _controller.Write(_pin, PinValue.Low);
        _isActive = false;
        await Task.CompletedTask;
    }
    
    public void Dispose()
    {
        _controller?.ClosePin(_pin);
    }
}

public class FanActuator : IActuator
{
    private readonly GpioController _controller;
    private readonly int _pin;
    private bool _isActive;
    
    public FanActuator(GpioController controller, int pin)
    {
        _controller = controller;
        _pin = pin;
        _controller.OpenPin(_pin, PinMode.Output);
        _controller.Write(_pin, PinValue.Low);
    }
    
    public bool IsActive => _isActive;
    
    public async Task ActivateAsync()
    {
        _controller.Write(_pin, PinValue.High);
        _isActive = true;
        await Task.CompletedTask;
    }
    
    public async Task DeactivateAsync()
    {
        _controller.Write(_pin, PinValue.Low);
        _isActive = false;
        await Task.CompletedTask;
    }
    
    public void Dispose()
    {
        _controller?.ClosePin(_pin);
    }
}

public class BuzzerActuator : IActuator
{
    private readonly GpioController _controller;
    private readonly int _pin;
    private bool _isActive;
    
    public BuzzerActuator(GpioController controller, int pin)
    {
        _controller = controller;
        _pin = pin;
        _controller.OpenPin(_pin, PinMode.Output);
        _controller.Write(_pin, PinValue.Low);
    }
    
    public bool IsActive => _isActive;
    
    public async Task ActivateAsync()
    {
        _controller.Write(_pin, PinValue.High);
        _isActive = true;
        await Task.CompletedTask;
    }
    
    public async Task DeactivateAsync()
    {
        _controller.Write(_pin, PinValue.Low);
        _isActive = false;
        await Task.CompletedTask;
    }
    
    public void Dispose()
    {
        _controller?.ClosePin(_pin);
    }
}

// 云数据服务
public interface ICloudDataService
{
    Task SendSensorDataAsync(Dictionary<string, object> sensorData);
    Task<DeviceConfiguration> GetDeviceConfigurationAsync(string deviceId);
    Task SendAlertAsync(string alertType, string message);
}

public class AzureIoTCloudService : ICloudDataService
{
    private readonly ILogger<AzureIoTCloudService> _logger;
    private readonly string _connectionString;
    
    public AzureIoTCloudService(ILogger<AzureIoTCloudService> logger, IConfiguration configuration)
    {
        _logger = logger;
        _connectionString = configuration.GetConnectionString("IoTHub");
    }
    
    public async Task SendSensorDataAsync(Dictionary<string, object> sensorData)
    {
        try
        {
            var telemetryData = new
            {
                DeviceId = Environment.MachineName,
                Timestamp = DateTime.UtcNow,
                Data = sensorData
            };
            
            var jsonData = JsonSerializer.Serialize(telemetryData);
            
            // 发送到 Azure IoT Hub
            // 实际实现需要使用 Azure IoT SDK
            _logger.LogInformation($"Sending telemetry data: {jsonData}");
            
            await Task.Delay(100); // 模拟网络延迟
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error sending sensor data to cloud");
        }
    }
    
    public async Task<DeviceConfiguration> GetDeviceConfigurationAsync(string deviceId)
    {
        try
        {
            // 从云端获取设备配置
            await Task.Delay(50);
            
            return new DeviceConfiguration
            {
                DeviceId = deviceId,
                SamplingInterval = TimeSpan.FromSeconds(5),
                TemperatureThreshold = 25.0,
                HumidityThreshold = 80.0,
                LightThreshold = 50.0
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting device configuration from cloud");
            return GetDefaultConfiguration();
        }
    }
    
    public async Task SendAlertAsync(string alertType, string message)
    {
        try
        {
            var alert = new
            {
                DeviceId = Environment.MachineName,
                AlertType = alertType,
                Message = message,
                Timestamp = DateTime.UtcNow,
                Severity = "Warning"
            };
            
            var jsonAlert = JsonSerializer.Serialize(alert);
            _logger.LogWarning($"Sending alert: {jsonAlert}");
            
            await Task.Delay(100);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error sending alert to cloud");
        }
    }
    
    private DeviceConfiguration GetDefaultConfiguration()
    {
        return new DeviceConfiguration
        {
            DeviceId = Environment.MachineName,
            SamplingInterval = TimeSpan.FromSeconds(10),
            TemperatureThreshold = 30.0,
            HumidityThreshold = 85.0,
            LightThreshold = 40.0
        };
    }
}

// 设备配置
public class DeviceConfiguration
{
    public string DeviceId { get; set; }
    public TimeSpan SamplingInterval { get; set; }
    public double TemperatureThreshold { get; set; }
    public double HumidityThreshold { get; set; }
    public double LightThreshold { get; set; }
}

边缘AI计算

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.Extensions.Logging;

// 边缘AI处理器
public class EdgeAIProcessor
{
    private readonly MLContext _mlContext;
    private readonly ILogger<EdgeAIProcessor> _logger;
    private readonly Dictionary<string, ITransformer> _models;
    private readonly EdgeAIConfiguration _configuration;
    
    public EdgeAIProcessor(ILogger<EdgeAIProcessor> logger, EdgeAIConfiguration configuration)
    {
        _mlContext = new MLContext(seed: 0);
        _logger = logger;
        _configuration = configuration;
        _models = new Dictionary<string, ITransformer>();
        
        LoadModels();
    }
    
    private void LoadModels()
    {
        try
        {
            // 加载预训练模型
            _models["anomaly_detection"] = _mlContext.Model.Load(_configuration.AnomalyModelPath, out _);
            _models["predictive_maintenance"] = _mlContext.Model.Load(_configuration.MaintenanceModelPath, out _);
            _models["quality_control"] = _mlContext.Model.Load(_configuration.QualityModelPath, out _);
            
            _logger.LogInformation("Edge AI models loaded successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error loading AI models");
        }
    }
    
    public async Task<AnomalyDetectionResult> DetectAnomalyAsync(SensorReading reading)
    {
        try
        {
            if (!_models.ContainsKey("anomaly_detection"))
            {
                throw new InvalidOperationException("Anomaly detection model not loaded");
            }
            
            var model = _models["anomaly_detection"];
            var predictionEngine = _mlContext.Model.CreatePredictionEngine<SensorReading, AnomalyPrediction>(model);
            
            var prediction = predictionEngine.Predict(reading);
            
            var result = new AnomalyDetectionResult
            {
                IsAnomaly = prediction.IsAnomaly,
                Score = prediction.Score,
                Timestamp = DateTime.UtcNow,
                SensorId = reading.SensorId,
                Confidence = CalculateConfidence(prediction.Score)
            };
            
            if (result.IsAnomaly)
            {
                _logger.LogWarning($"Anomaly detected on sensor {reading.SensorId}: Score={result.Score:F3}");
                await TriggerAnomalyResponseAsync(result);
            }
            
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in anomaly detection");
            return new AnomalyDetectionResult { IsAnomaly = false, Score = 0 };
        }
    }
    
    public async Task<MaintenancePrediction> PredictMaintenanceAsync(EquipmentData equipment)
    {
        try
        {
            if (!_models.ContainsKey("predictive_maintenance"))
            {
                throw new InvalidOperationException("Maintenance prediction model not loaded");
            }
            
            var model = _models["predictive_maintenance"];
            var predictionEngine = _mlContext.Model.CreatePredictionEngine<EquipmentData, MaintenancePrediction>(model);
            
            var prediction = predictionEngine.Predict(equipment);
            
            if (prediction.DaysUntilMaintenance <= _configuration.MaintenanceThresholdDays)
            {
                _logger.LogInformation($"Maintenance required for equipment {equipment.EquipmentId} in {prediction.DaysUntilMaintenance} days");
                await ScheduleMaintenanceAsync(equipment.EquipmentId, prediction.DaysUntilMaintenance);
            }
            
            return prediction;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in maintenance prediction");
            return new MaintenancePrediction { DaysUntilMaintenance = 365 };
        }
    }
    
    public async Task<QualityAssessment> AssessQualityAsync(ProductData product)
    {
        try
        {
            if (!_models.ContainsKey("quality_control"))
            {
                throw new InvalidOperationException("Quality control model not loaded");
            }
            
            var model = _models["quality_control"];
            var predictionEngine = _mlContext.Model.CreatePredictionEngine<ProductData, QualityPrediction>(model);
            
            var prediction = predictionEngine.Predict(product);
            
            var assessment = new QualityAssessment
            {
                ProductId = product.ProductId,
                QualityScore = prediction.QualityScore,
                IsDefective = prediction.QualityScore < _configuration.QualityThreshold,
                Timestamp = DateTime.UtcNow,
                Recommendations = GenerateQualityRecommendations(prediction)
            };
            
            if (assessment.IsDefective)
            {
                _logger.LogWarning($"Quality issue detected for product {product.ProductId}: Score={assessment.QualityScore:F3}");
                await HandleQualityIssueAsync(assessment);
            }
            
            return assessment;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in quality assessment");
            return new QualityAssessment { QualityScore = 0, IsDefective = true };
        }
    }
    
    private float CalculateConfidence(float score)
    {
        return Math.Min(1.0f, Math.Abs(score) * 2.0f);
    }
    
    private async Task TriggerAnomalyResponseAsync(AnomalyDetectionResult result)
    {
        // 触发异常响应
        await Task.Delay(10); // 模拟响应时间
        _logger.LogInformation($"Anomaly response triggered for sensor {result.SensorId}");
    }
    
    private async Task ScheduleMaintenanceAsync(string equipmentId, float daysUntilMaintenance)
    {
        // 安排维护
        await Task.Delay(10);
        _logger.LogInformation($"Maintenance scheduled for equipment {equipmentId} in {daysUntilMaintenance} days");
    }
    
    private async Task HandleQualityIssueAsync(QualityAssessment assessment)
    {
        // 处理质量问题
        await Task.Delay(10);
        _logger.LogInformation($"Quality issue handling initiated for product {assessment.ProductId}");
    }
    
    private List<string> GenerateQualityRecommendations(QualityPrediction prediction)
    {
        var recommendations = new List<string>();
        
        if (prediction.QualityScore < 0.5f)
        {
            recommendations.Add("Immediate quality inspection required");
            recommendations.Add("Check production parameters");
        }
        else if (prediction.QualityScore < 0.7f)
        {
            recommendations.Add("Monitor production closely");
            recommendations.Add("Consider process adjustment");
        }
        
        return recommendations;
    }
}

// 边缘AI配置
public class EdgeAIConfiguration
{
    public string AnomalyModelPath { get; set; }
    public string MaintenanceModelPath { get; set; }
    public string QualityModelPath { get; set; }
    public int MaintenanceThresholdDays { get; set; } = 7;
    public float QualityThreshold { get; set; } = 0.8f;
}

// 数据模型
public class SensorReading
{
    [LoadColumn(0)]
    public string SensorId { get; set; }
    
    [LoadColumn(1)]
    public float Temperature { get; set; }
    
    [LoadColumn(2)]
    public float Pressure { get; set; }
    
    [LoadColumn(3)]
    public float Vibration { get; set; }
    
    [LoadColumn(4)]
    public float Humidity { get; set; }
}

public class AnomalyPrediction
{
    [ColumnName("PredictedLabel")]
    public bool IsAnomaly { get; set; }
    
    [ColumnName("Score")]
    public float Score { get; set; }
}

public class AnomalyDetectionResult
{
    public bool IsAnomaly { get; set; }
    public float Score { get; set; }
    public float Confidence { get; set; }
    public DateTime Timestamp { get; set; }
    public string SensorId { get; set; }
}

public class EquipmentData
{
    [LoadColumn(0)]
    public string EquipmentId { get; set; }
    
    [LoadColumn(1)]
    public float OperatingHours { get; set; }
    
    [LoadColumn(2)]
    public float MaintenanceHistory { get; set; }
    
    [LoadColumn(3)]
    public float PerformanceMetric { get; set; }
    
    [LoadColumn(4)]
    public float ErrorRate { get; set; }
}

public class MaintenancePrediction
{
    [ColumnName("Score")]
    public float DaysUntilMaintenance { get; set; }
}

public class ProductData
{
    [LoadColumn(0)]
    public string ProductId { get; set; }
    
    [LoadColumn(1)]
    public float Dimension1 { get; set; }
    
    [LoadColumn(2)]
    public float Dimension2 { get; set; }
    
    [LoadColumn(3)]
    public float Weight { get; set; }
    
    [LoadColumn(4)]
    public float Density { get; set; }
}

public class QualityPrediction
{
    [ColumnName("Score")]
    public float QualityScore { get; set; }
}

public class QualityAssessment
{
    public string ProductId { get; set; }
    public float QualityScore { get; set; }
    public bool IsDefective { get; set; }
    public DateTime Timestamp { get; set; }
    public List<string> Recommendations { get; set; }
}

25.3 现代化技术栈

.NET 8+ 新特性应用

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text.Json;
using System.ComponentModel.DataAnnotations;

// .NET 8+ 新特性演示
public class ModernCSharpFeatures
{
    // 原始字符串字面量
    private static readonly string JsonTemplate = """
        {
            "name": "{name}",
            "age": {age},
            "email": "{email}",
            "created": "{created}"
        }
        """;
    
    // 必需成员
    public required string Name { get; init; }
    public required int Age { get; init; }
    public string? Email { get; init; }
    
    // 静态抽象成员
    public static abstract class MathOperations<T> where T : INumber<T>
    {
        public static abstract T Add(T left, T right);
        public static abstract T Multiply(T left, T right);
    }
    
    // 泛型数学
    public static T CalculateAverage<T>(IEnumerable<T> values) where T : INumber<T>
    {
        var sum = T.Zero;
        var count = 0;
        
        foreach (var value in values)
        {
            sum += value;
            count++;
        }
        
        return count > 0 ? sum / T.CreateChecked(count) : T.Zero;
    }
    
    // UTF-8 字符串字面量
    private static ReadOnlySpan<byte> Utf8String => "Hello, World!"u8;
    
    // 列表模式
    public static string AnalyzeList<T>(IList<T> list) => list switch
    {
        [] => "Empty list",
        [var single] => $"Single item: {single}",
        [var first, var second] => $"Two items: {first}, {second}",
        [var first, .., var last] => $"Multiple items from {first} to {last}",
        _ => "Unknown pattern"
    };
    
    // 改进的插值字符串
    public static string FormatCurrency(decimal amount, string currency = "USD")
    {
        return $"Amount: {amount:C} {currency}";
    }
    
    // 文件范围命名空间和全局using
    public class ApiResponse<T>
    {
        public bool Success { get; init; }
        public T? Data { get; init; }
        public string? ErrorMessage { get; init; }
        public DateTime Timestamp { get; init; } = DateTime.UtcNow;
        
        public static ApiResponse<T> SuccessResult(T data) => new()
        {
            Success = true,
            Data = data
        };
        
        public static ApiResponse<T> ErrorResult(string message) => new()
        {
            Success = false,
            ErrorMessage = message
        };
    }
}

// 最小API示例
public class MinimalApiExample
{
    public static void ConfigureMinimalApi(WebApplication app)
    {
        // 简单的GET端点
        app.MapGet("/api/users", async (IUserService userService) =>
        {
            var users = await userService.GetAllUsersAsync();
            return Results.Ok(users);
        });
        
        // 带参数的GET端点
        app.MapGet("/api/users/{id:int}", async (int id, IUserService userService) =>
        {
            var user = await userService.GetUserByIdAsync(id);
            return user is not null ? Results.Ok(user) : Results.NotFound();
        });
        
        // POST端点
        app.MapPost("/api/users", async (CreateUserRequest request, IUserService userService) =>
        {
            var user = await userService.CreateUserAsync(request);
            return Results.Created($"/api/users/{user.Id}", user);
        })
        .WithName("CreateUser")
        .WithOpenApi()
        .Produces<User>(StatusCodes.Status201Created)
        .ProducesValidationProblem();
        
        // PUT端点
        app.MapPut("/api/users/{id:int}", async (int id, UpdateUserRequest request, IUserService userService) =>
        {
            var updated = await userService.UpdateUserAsync(id, request);
            return updated ? Results.NoContent() : Results.NotFound();
        });
        
        // DELETE端点
        app.MapDelete("/api/users/{id:int}", async (int id, IUserService userService) =>
        {
            var deleted = await userService.DeleteUserAsync(id);
            return deleted ? Results.NoContent() : Results.NotFound();
        });
        
        // 文件上传端点
        app.MapPost("/api/upload", async (IFormFile file, IFileService fileService) =>
        {
            if (file.Length == 0)
                return Results.BadRequest("No file uploaded");
            
            var result = await fileService.SaveFileAsync(file);
            return Results.Ok(new { FileName = result.FileName, Size = result.Size });
        })
        .DisableAntiforgery();
        
        // 实时通信端点
        app.MapHub<ChatHub>("/chathub");
        
        // 健康检查端点
        app.MapHealthChecks("/health");
    }
}

// 现代化数据访问
public class ModernDataAccess
{
    private readonly IDbContextFactory<AppDbContext> _contextFactory;
    private readonly ILogger<ModernDataAccess> _logger;
    
    public ModernDataAccess(IDbContextFactory<AppDbContext> contextFactory, ILogger<ModernDataAccess> logger)
    {
        _contextFactory = contextFactory;
        _logger = logger;
    }
    
    // 异步枚举
    public async IAsyncEnumerable<User> GetUsersStreamAsync([EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        await using var context = await _contextFactory.CreateDbContextAsync(cancellationToken);
        
        await foreach (var user in context.Users.AsAsyncEnumerable().WithCancellation(cancellationToken))
        {
            yield return user;
        }
    }
    
    // 批量操作
    public async Task<int> BulkUpdateUsersAsync(IEnumerable<User> users, CancellationToken cancellationToken = default)
    {
        await using var context = await _contextFactory.CreateDbContextAsync(cancellationToken);
        
        context.Users.UpdateRange(users);
        return await context.SaveChangesAsync(cancellationToken);
    }
    
    // 原始SQL查询
    public async Task<IEnumerable<UserStatistics>> GetUserStatisticsAsync(CancellationToken cancellationToken = default)
    {
        await using var context = await _contextFactory.CreateDbContextAsync(cancellationToken);
        
        return await context.Database
            .SqlQuery<UserStatistics>($"""
                SELECT 
                    u.Id,
                    u.Name,
                    COUNT(o.Id) as OrderCount,
                    SUM(o.Amount) as TotalAmount
                FROM Users u
                LEFT JOIN Orders o ON u.Id = o.UserId
                GROUP BY u.Id, u.Name
                """)
            .ToListAsync(cancellationToken);
    }
    
    // 事务处理
    public async Task<bool> TransferFundsAsync(int fromUserId, int toUserId, decimal amount, CancellationToken cancellationToken = default)
    {
        await using var context = await _contextFactory.CreateDbContextAsync(cancellationToken);
        await using var transaction = await context.Database.BeginTransactionAsync(cancellationToken);
        
        try
        {
            var fromUser = await context.Users.FindAsync(new object[] { fromUserId }, cancellationToken);
            var toUser = await context.Users.FindAsync(new object[] { toUserId }, cancellationToken);
            
            if (fromUser?.Balance < amount)
                return false;
            
            fromUser.Balance -= amount;
            toUser.Balance += amount;
            
            await context.SaveChangesAsync(cancellationToken);
            await transaction.CommitAsync(cancellationToken);
            
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error during fund transfer");
            await transaction.RollbackAsync(cancellationToken);
            return false;
        }
    }
}

// 现代化配置和选项
public class ModernConfiguration
{
    public class AppSettings
    {
        public const string SectionName = "App";
        
        [Required]
        public string ApplicationName { get; set; } = string.Empty;
        
        [Range(1, 3600)]
        public int CacheExpirationSeconds { get; set; } = 300;
        
        [Required, Url]
        public string ApiBaseUrl { get; set; } = string.Empty;
        
        public DatabaseSettings Database { get; set; } = new();
        public LoggingSettings Logging { get; set; } = new();
    }
    
    public class DatabaseSettings
    {
        [Required]
        public string ConnectionString { get; set; } = string.Empty;
        
        [Range(1, 100)]
        public int MaxRetryAttempts { get; set; } = 3;
        
        public bool EnableSensitiveDataLogging { get; set; } = false;
    }
    
    public class LoggingSettings
    {
        public LogLevel MinimumLevel { get; set; } = LogLevel.Information;
        public bool EnableStructuredLogging { get; set; } = true;
        public string LogFilePath { get; set; } = "logs/app.log";
    }
}

// 现代化依赖注入
public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddModernServices(this IServiceCollection services, IConfiguration configuration)
    {
        // 选项模式
        services.Configure<ModernConfiguration.AppSettings>(configuration.GetSection(ModernConfiguration.AppSettings.SectionName));
        services.AddOptionsWithValidateOnStart<ModernConfiguration.AppSettings>();
        
        // 键控服务
        services.AddKeyedScoped<INotificationService, EmailNotificationService>("email");
        services.AddKeyedScoped<INotificationService, SmsNotificationService>("sms");
        services.AddKeyedScoped<INotificationService, PushNotificationService>("push");
        
        // 工厂模式
        services.AddSingleton<INotificationServiceFactory, NotificationServiceFactory>();
        
        // 装饰器模式
        services.Decorate<IUserService, CachedUserService>();
        services.Decorate<IUserService, LoggingUserService>();
        
        // 条件注册
        if (configuration.GetValue<bool>("Features:EnableAdvancedLogging"))
        {
            services.AddScoped<IAdvancedLogger, AdvancedLogger>();
        }
        
        return services;
    }
}

// 数据模型
public record User(int Id, string Name, string Email, decimal Balance);
public record CreateUserRequest(string Name, string Email);
public record UpdateUserRequest(string Name, string Email);
public record UserStatistics(int Id, string Name, int OrderCount, decimal TotalAmount);

// 服务接口
public interface IUserService
{
    Task<IEnumerable<User>> GetAllUsersAsync();
    Task<User?> GetUserByIdAsync(int id);
    Task<User> CreateUserAsync(CreateUserRequest request);
    Task<bool> UpdateUserAsync(int id, UpdateUserRequest request);
    Task<bool> DeleteUserAsync(int id);
}

public interface IFileService
{
    Task<FileUploadResult> SaveFileAsync(IFormFile file);
}

public interface INotificationService
{
    Task SendNotificationAsync(string recipient, string message);
}

public interface INotificationServiceFactory
{
    INotificationService GetService(string type);
}

public record FileUploadResult(string FileName, long Size);

Blazor 全栈开发

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.JSInterop;
using System.ComponentModel.DataAnnotations;

// Blazor Server 组件
@page "/users"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
@inject IUserService UserService
@inject IJSRuntime JSRuntime
@inject NavigationManager Navigation

<PageTitle>用户管理</PageTitle>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h3 class="mb-0">用户管理</h3>
                    <button class="btn btn-primary" @onclick="ShowCreateModal">
                        <i class="fas fa-plus"></i> 新增用户
                    </button>
                </div>
                <div class="card-body">
                    <!-- 搜索和筛选 -->
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="搜索用户..." 
                                       @bind="searchTerm" @onkeypress="OnSearchKeyPress" />
                                <button class="btn btn-outline-secondary" @onclick="SearchUsers">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <select class="form-select" @bind="selectedRole">
                                <option value="">所有角色</option>
                                <option value="Admin">管理员</option>
                                <option value="User">普通用户</option>
                            </select>
                        </div>
                    </div>
                    
                    <!-- 用户列表 -->
                    @if (isLoading)
                    {
                        <div class="text-center">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </div>
                    }
                    else if (users?.Any() == true)
                    {
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th>ID</th>
                                        <th>姓名</th>
                                        <th>邮箱</th>
                                        <th>角色</th>
                                        <th>状态</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach (var user in users)
                                    {
                                        <tr>
                                            <td>@user.Id</td>
                                            <td>@user.Name</td>
                                            <td>@user.Email</td>
                                            <td>
                                                <span class="badge bg-@(user.Role == "Admin" ? "danger" : "primary")">
                                                    @user.Role
                                                </span>
                                            </td>
                                            <td>
                                                <span class="badge bg-@(user.IsActive ? "success" : "secondary")">
                                                    @(user.IsActive ? "活跃" : "禁用")
                                                </span>
                                            </td>
                                            <td>@user.CreatedAt.ToString("yyyy-MM-dd")</td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <button class="btn btn-sm btn-outline-primary" 
                                                            @onclick="() => EditUser(user)">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <button class="btn btn-sm btn-outline-danger" 
                                                            @onclick="() => DeleteUser(user.Id)">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    }
                                </tbody>
                            </table>
                        </div>
                        
                        <!-- 分页 -->
                        <nav>
                            <ul class="pagination justify-content-center">
                                <li class="page-item @(currentPage == 1 ? "disabled" : "")">
                                    <button class="page-link" @onclick="() => ChangePage(currentPage - 1)">
                                        上一页
                                    </button>
                                </li>
                                @for (int i = 1; i <= totalPages; i++)
                                {
                                    var page = i;
                                    <li class="page-item @(currentPage == page ? "active" : "")">
                                        <button class="page-link" @onclick="() => ChangePage(page)">
                                            @page
                                        </button>
                                    </li>
                                }
                                <li class="page-item @(currentPage == totalPages ? "disabled" : "")">
                                    <button class="page-link" @onclick="() => ChangePage(currentPage + 1)">
                                        下一页
                                    </button>
                                </li>
                            </ul>
                        </nav>
                    }
                    else
                    {
                        <div class="text-center text-muted">
                            <i class="fas fa-users fa-3x mb-3"></i>
                            <p>暂无用户数据</p>
                        </div>
                    }
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 用户编辑模态框 -->
<div class="modal fade @(showModal ? "show" : "")" style="display: @(showModal ? "block" : "none")">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">@(editingUser?.Id > 0 ? "编辑用户" : "新增用户")</h5>
                <button type="button" class="btn-close" @onclick="CloseModal"></button>
            </div>
            <EditForm Model="editingUser" OnValidSubmit="SaveUser">
                <DataAnnotationsValidator />
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">姓名</label>
                                <InputText class="form-control" @bind-Value="editingUser.Name" />
                                <ValidationMessage For="() => editingUser.Name" />
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">邮箱</label>
                                <InputText class="form-control" @bind-Value="editingUser.Email" />
                                <ValidationMessage For="() => editingUser.Email" />
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">角色</label>
                                <InputSelect class="form-select" @bind-Value="editingUser.Role">
                                    <option value="User">普通用户</option>
                                    <option value="Admin">管理员</option>
                                </InputSelect>
                                <ValidationMessage For="() => editingUser.Role" />
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <div class="form-check">
                                    <InputCheckbox class="form-check-input" @bind-Value="editingUser.IsActive" />
                                    <label class="form-check-label">激活状态</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @onclick="CloseModal">取消</button>
                    <button type="submit" class="btn btn-primary" disabled="@isSaving">
                        @if (isSaving)
                        {
                            <span class="spinner-border spinner-border-sm me-2"></span>
                        }
                        保存
                    </button>
                </div>
            </EditForm>
        </div>
    </div>
</div>

@code {
    private List<UserViewModel>? users;
    private UserViewModel editingUser = new();
    private string searchTerm = string.Empty;
    private string selectedRole = string.Empty;
    private bool isLoading = true;
    private bool showModal = false;
    private bool isSaving = false;
    private int currentPage = 1;
    private int totalPages = 1;
    private const int PageSize = 10;
    
    protected override async Task OnInitializedAsync()
    {
        await LoadUsers();
    }
    
    private async Task LoadUsers()
    {
        isLoading = true;
        try
        {
            var result = await UserService.GetUsersAsync(currentPage, PageSize, searchTerm, selectedRole);
            users = result.Items.ToList();
            totalPages = (int)Math.Ceiling((double)result.TotalCount / PageSize);
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("alert", $"加载用户失败: {ex.Message}");
        }
        finally
        {
            isLoading = false;
        }
    }
    
    private async Task SearchUsers()
    {
        currentPage = 1;
        await LoadUsers();
    }
    
    private async Task OnSearchKeyPress(KeyboardEventArgs e)
    {
        if (e.Key == "Enter")
        {
            await SearchUsers();
        }
    }
    
    private async Task ChangePage(int page)
    {
        if (page >= 1 && page <= totalPages)
        {
            currentPage = page;
            await LoadUsers();
        }
    }
    
    private void ShowCreateModal()
    {
        editingUser = new UserViewModel();
        showModal = true;
    }
    
    private void EditUser(UserViewModel user)
    {
        editingUser = new UserViewModel
        {
            Id = user.Id,
            Name = user.Name,
            Email = user.Email,
            Role = user.Role,
            IsActive = user.IsActive
        };
        showModal = true;
    }
    
    private void CloseModal()
    {
        showModal = false;
        editingUser = new UserViewModel();
    }
    
    private async Task SaveUser()
    {
        isSaving = true;
        try
        {
            if (editingUser.Id > 0)
            {
                await UserService.UpdateUserAsync(editingUser.Id, editingUser);
            }
            else
            {
                await UserService.CreateUserAsync(editingUser);
            }
            
            await LoadUsers();
            CloseModal();
            await JSRuntime.InvokeVoidAsync("showToast", "用户保存成功", "success");
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("showToast", $"保存失败: {ex.Message}", "error");
        }
        finally
        {
            isSaving = false;
        }
    }
    
    private async Task DeleteUser(int userId)
    {
        var confirmed = await JSRuntime.InvokeAsync<bool>("confirm", "确定要删除这个用户吗?");
        if (confirmed)
        {
            try
            {
                await UserService.DeleteUserAsync(userId);
                await LoadUsers();
                await JSRuntime.InvokeVoidAsync("showToast", "用户删除成功", "success");
            }
            catch (Exception ex)
            {
                await JSRuntime.InvokeVoidAsync("showToast", $"删除失败: {ex.Message}", "error");
            }
        }
    }
}

// Blazor WebAssembly 组件
public class BlazorWasmComponent : ComponentBase
{
    [Inject] public HttpClient Http { get; set; } = default!;
    [Inject] public IJSRuntime JSRuntime { get; set; } = default!;
    [Inject] public ILocalStorageService LocalStorage { get; set; } = default!;
    
    protected List<ProductViewModel> products = new();
    protected bool isLoading = true;
    protected string errorMessage = string.Empty;
    
    protected override async Task OnInitializedAsync()
    {
        await LoadProducts();
    }
    
    protected async Task LoadProducts()
    {
        try
        {
            isLoading = true;
            errorMessage = string.Empty;
            
            // 从本地存储获取认证令牌
            var token = await LocalStorage.GetItemAsync<string>("authToken");
            if (!string.IsNullOrEmpty(token))
            {
                Http.DefaultRequestHeaders.Authorization = 
                    new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            }
            
            // 调用API
            var response = await Http.GetFromJsonAsync<ApiResponse<List<ProductViewModel>>>("/api/products");
            
            if (response?.Success == true && response.Data != null)
            {
                products = response.Data;
            }
            else
            {
                errorMessage = response?.ErrorMessage ?? "加载产品失败";
            }
        }
        catch (HttpRequestException ex)
        {
            errorMessage = $"网络错误: {ex.Message}";
        }
        catch (Exception ex)
        {
            errorMessage = $"未知错误: {ex.Message}";
        }
        finally
        {
            isLoading = false;
            StateHasChanged();
        }
    }
    
    protected async Task AddToCart(int productId)
    {
        try
        {
            var cartItem = new { ProductId = productId, Quantity = 1 };
            var response = await Http.PostAsJsonAsync("/api/cart/items", cartItem);
            
            if (response.IsSuccessStatusCode)
            {
                await JSRuntime.InvokeVoidAsync("showNotification", "商品已添加到购物车", "success");
            }
            else
            {
                await JSRuntime.InvokeVoidAsync("showNotification", "添加失败", "error");
            }
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("showNotification", $"操作失败: {ex.Message}", "error");
        }
    }
}

// Blazor 混合应用
public class BlazorHybridService
{
    private readonly HttpClient _httpClient;
    private readonly IConnectivity _connectivity;
    private readonly ISecureStorage _secureStorage;
    private readonly ILogger<BlazorHybridService> _logger;
    
    public BlazorHybridService(
        HttpClient httpClient,
        IConnectivity connectivity,
        ISecureStorage secureStorage,
        ILogger<BlazorHybridService> logger)
    {
        _httpClient = httpClient;
        _connectivity = connectivity;
        _secureStorage = secureStorage;
        _logger = logger;
    }
    
    public async Task<List<DataModel>> GetDataAsync(bool forceRefresh = false)
    {
        try
        {
            // 检查网络连接
            if (_connectivity.NetworkAccess != NetworkAccess.Internet)
            {
                _logger.LogWarning("No internet connection, loading from cache");
                return await LoadFromCacheAsync();
            }
            
            // 在线获取数据
            var response = await _httpClient.GetFromJsonAsync<List<DataModel>>("/api/data");
            
            if (response != null)
            {
                // 缓存数据
                await CacheDataAsync(response);
                return response;
            }
            
            // 如果在线获取失败,尝试从缓存加载
            return await LoadFromCacheAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error loading data");
            return await LoadFromCacheAsync();
        }
    }
    
    private async Task<List<DataModel>> LoadFromCacheAsync()
    {
        try
        {
            var cachedData = await _secureStorage.GetAsync("cached_data");
            if (!string.IsNullOrEmpty(cachedData))
            {
                return JsonSerializer.Deserialize<List<DataModel>>(cachedData) ?? new List<DataModel>();
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error loading from cache");
        }
        
        return new List<DataModel>();
    }
    
    private async Task CacheDataAsync(List<DataModel> data)
    {
        try
        {
            var json = JsonSerializer.Serialize(data);
            await _secureStorage.SetAsync("cached_data", json);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error caching data");
        }
    }
}

// 数据模型
public class UserViewModel
{
    public int Id { get; set; }
    
    [Required(ErrorMessage = "姓名不能为空")]
    [StringLength(50, ErrorMessage = "姓名长度不能超过50个字符")]
    public string Name { get; set; } = string.Empty;
    
    [Required(ErrorMessage = "邮箱不能为空")]
    [EmailAddress(ErrorMessage = "邮箱格式不正确")]
    public string Email { get; set; } = string.Empty;
    
    [Required(ErrorMessage = "角色不能为空")]
    public string Role { get; set; } = "User";
    
    public bool IsActive { get; set; } = true;
    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}

public class ProductViewModel
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public string ImageUrl { get; set; } = string.Empty;
    public bool InStock { get; set; }
}

public class DataModel
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public DateTime LastUpdated { get; set; }
}

public class PagedResult<T>
{
    public IEnumerable<T> Items { get; set; } = Enumerable.Empty<T>();
    public int TotalCount { get; set; }
    public int PageNumber { get; set; }
    public int PageSize { get; set; }
}

gRPC 和现代 API 设计

using Grpc.Core;
using Grpc.Net.Client;
using Microsoft.AspNetCore.Authorization;
using System.ComponentModel.DataAnnotations;
using Google.Protobuf.WellKnownTypes;

// gRPC 服务定义 (user.proto)
/*
syntax = "proto3";

option csharp_namespace = "ModernApi.Grpc";

package user;

service UserService {
  rpc GetUser (GetUserRequest) returns (UserResponse);
  rpc GetUsers (GetUsersRequest) returns (stream UserResponse);
  rpc CreateUser (CreateUserRequest) returns (UserResponse);
  rpc UpdateUser (UpdateUserRequest) returns (UserResponse);
  rpc DeleteUser (DeleteUserRequest) returns (google.protobuf.Empty);
  rpc SearchUsers (SearchUsersRequest) returns (SearchUsersResponse);
}

message GetUserRequest {
  int32 id = 1;
}

message GetUsersRequest {
  int32 page = 1;
  int32 page_size = 2;
}

message CreateUserRequest {
  string name = 1;
  string email = 2;
  string role = 3;
}

message UpdateUserRequest {
  int32 id = 1;
  string name = 2;
  string email = 3;
  string role = 4;
  bool is_active = 5;
}

message DeleteUserRequest {
  int32 id = 1;
}

message SearchUsersRequest {
  string query = 1;
  repeated string roles = 2;
  int32 page = 3;
  int32 page_size = 4;
}

message UserResponse {
  int32 id = 1;
  string name = 2;
  string email = 3;
  string role = 4;
  bool is_active = 5;
  google.protobuf.Timestamp created_at = 6;
  google.protobuf.Timestamp updated_at = 7;
}

message SearchUsersResponse {
  repeated UserResponse users = 1;
  int32 total_count = 2;
  int32 page = 3;
  int32 page_size = 4;
}
*/

// gRPC 服务实现
[Authorize]
public class UserGrpcService : UserService.UserServiceBase
{
    private readonly IUserRepository _userRepository;
    private readonly IMapper _mapper;
    private readonly ILogger<UserGrpcService> _logger;
    private readonly IValidator<CreateUserRequest> _createValidator;
    private readonly IValidator<UpdateUserRequest> _updateValidator;
    
    public UserGrpcService(
        IUserRepository userRepository,
        IMapper mapper,
        ILogger<UserGrpcService> logger,
        IValidator<CreateUserRequest> createValidator,
        IValidator<UpdateUserRequest> updateValidator)
    {
        _userRepository = userRepository;
        _mapper = mapper;
        _logger = logger;
        _createValidator = createValidator;
        _updateValidator = updateValidator;
    }
    
    public override async Task<UserResponse> GetUser(GetUserRequest request, ServerCallContext context)
    {
        try
        {
            _logger.LogInformation("Getting user with ID: {UserId}", request.Id);
            
            var user = await _userRepository.GetByIdAsync(request.Id);
            if (user == null)
            {
                throw new RpcException(new Status(StatusCode.NotFound, $"User with ID {request.Id} not found"));
            }
            
            return _mapper.Map<UserResponse>(user);
        }
        catch (Exception ex) when (!(ex is RpcException))
        {
            _logger.LogError(ex, "Error getting user with ID: {UserId}", request.Id);
            throw new RpcException(new Status(StatusCode.Internal, "Internal server error"));
        }
    }
    
    public override async Task GetUsers(GetUsersRequest request, IServerStreamWriter<UserResponse> responseStream, ServerCallContext context)
    {
        try
        {
            _logger.LogInformation("Streaming users - Page: {Page}, PageSize: {PageSize}", request.Page, request.PageSize);
            
            var users = _userRepository.GetUsersAsync(request.Page, request.PageSize);
            
            await foreach (var user in users.WithCancellation(context.CancellationToken))
            {
                var userResponse = _mapper.Map<UserResponse>(user);
                await responseStream.WriteAsync(userResponse);
                
                // 模拟延迟以演示流式传输
                await Task.Delay(100, context.CancellationToken);
            }
        }
        catch (OperationCanceledException)
        {
            _logger.LogInformation("User streaming cancelled");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error streaming users");
            throw new RpcException(new Status(StatusCode.Internal, "Error streaming users"));
        }
    }
    
    public override async Task<UserResponse> CreateUser(CreateUserRequest request, ServerCallContext context)
    {
        try
        {
            // 验证请求
            var validationResult = await _createValidator.ValidateAsync(request);
            if (!validationResult.IsValid)
            {
                var errors = string.Join(", ", validationResult.Errors.Select(e => e.ErrorMessage));
                throw new RpcException(new Status(StatusCode.InvalidArgument, errors));
            }
            
            _logger.LogInformation("Creating user: {UserName}", request.Name);
            
            var user = _mapper.Map<User>(request);
            var createdUser = await _userRepository.CreateAsync(user);
            
            _logger.LogInformation("User created successfully with ID: {UserId}", createdUser.Id);
            return _mapper.Map<UserResponse>(createdUser);
        }
        catch (Exception ex) when (!(ex is RpcException))
        {
            _logger.LogError(ex, "Error creating user: {UserName}", request.Name);
            throw new RpcException(new Status(StatusCode.Internal, "Error creating user"));
        }
    }
    
    public override async Task<UserResponse> UpdateUser(UpdateUserRequest request, ServerCallContext context)
    {
        try
        {
            // 验证请求
            var validationResult = await _updateValidator.ValidateAsync(request);
            if (!validationResult.IsValid)
            {
                var errors = string.Join(", ", validationResult.Errors.Select(e => e.ErrorMessage));
                throw new RpcException(new Status(StatusCode.InvalidArgument, errors));
            }
            
            _logger.LogInformation("Updating user with ID: {UserId}", request.Id);
            
            var existingUser = await _userRepository.GetByIdAsync(request.Id);
            if (existingUser == null)
            {
                throw new RpcException(new Status(StatusCode.NotFound, $"User with ID {request.Id} not found"));
            }
            
            _mapper.Map(request, existingUser);
            var updatedUser = await _userRepository.UpdateAsync(existingUser);
            
            _logger.LogInformation("User updated successfully: {UserId}", request.Id);
            return _mapper.Map<UserResponse>(updatedUser);
        }
        catch (Exception ex) when (!(ex is RpcException))
        {
            _logger.LogError(ex, "Error updating user with ID: {UserId}", request.Id);
            throw new RpcException(new Status(StatusCode.Internal, "Error updating user"));
        }
    }
    
    public override async Task<Empty> DeleteUser(DeleteUserRequest request, ServerCallContext context)
    {
        try
        {
            _logger.LogInformation("Deleting user with ID: {UserId}", request.Id);
            
            var user = await _userRepository.GetByIdAsync(request.Id);
            if (user == null)
            {
                throw new RpcException(new Status(StatusCode.NotFound, $"User with ID {request.Id} not found"));
            }
            
            await _userRepository.DeleteAsync(request.Id);
            
            _logger.LogInformation("User deleted successfully: {UserId}", request.Id);
            return new Empty();
        }
        catch (Exception ex) when (!(ex is RpcException))
        {
            _logger.LogError(ex, "Error deleting user with ID: {UserId}", request.Id);
            throw new RpcException(new Status(StatusCode.Internal, "Error deleting user"));
        }
    }
    
    public override async Task<SearchUsersResponse> SearchUsers(SearchUsersRequest request, ServerCallContext context)
    {
        try
        {
            _logger.LogInformation("Searching users with query: {Query}", request.Query);
            
            var searchResult = await _userRepository.SearchAsync(
                request.Query,
                request.Roles.ToList(),
                request.Page,
                request.PageSize);
            
            var response = new SearchUsersResponse
            {
                TotalCount = searchResult.TotalCount,
                Page = request.Page,
                PageSize = request.PageSize
            };
            
            response.Users.AddRange(searchResult.Users.Select(_mapper.Map<UserResponse>));
            
            return response;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error searching users with query: {Query}", request.Query);
            throw new RpcException(new Status(StatusCode.Internal, "Error searching users"));
        }
    }
}

// gRPC 客户端
public class UserGrpcClient
{
    private readonly UserService.UserServiceClient _client;
    private readonly ILogger<UserGrpcClient> _logger;
    
    public UserGrpcClient(GrpcChannel channel, ILogger<UserGrpcClient> logger)
    {
        _client = new UserService.UserServiceClient(channel);
        _logger = logger;
    }
    
    public async Task<UserResponse?> GetUserAsync(int id, CancellationToken cancellationToken = default)
    {
        try
        {
            var request = new GetUserRequest { Id = id };
            return await _client.GetUserAsync(request, cancellationToken: cancellationToken);
        }
        catch (RpcException ex) when (ex.StatusCode == StatusCode.NotFound)
        {
            return null;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting user with ID: {UserId}", id);
            throw;
        }
    }
    
    public async Task<List<UserResponse>> GetUsersStreamAsync(int page = 1, int pageSize = 10, CancellationToken cancellationToken = default)
    {
        var users = new List<UserResponse>();
        
        try
        {
            var request = new GetUsersRequest { Page = page, PageSize = pageSize };
            
            using var call = _client.GetUsers(request, cancellationToken: cancellationToken);
            
            await foreach (var user in call.ResponseStream.ReadAllAsync(cancellationToken))
            {
                users.Add(user);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error streaming users");
            throw;
        }
        
        return users;
    }
    
    public async Task<UserResponse> CreateUserAsync(string name, string email, string role, CancellationToken cancellationToken = default)
    {
        try
        {
            var request = new CreateUserRequest
            {
                Name = name,
                Email = email,
                Role = role
            };
            
            return await _client.CreateUserAsync(request, cancellationToken: cancellationToken);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error creating user: {UserName}", name);
            throw;
        }
    }
    
    public async Task<SearchUsersResponse> SearchUsersAsync(string query, List<string> roles, int page = 1, int pageSize = 10, CancellationToken cancellationToken = default)
    {
        try
        {
            var request = new SearchUsersRequest
            {
                Query = query,
                Page = page,
                PageSize = pageSize
            };
            
            request.Roles.AddRange(roles);
            
            return await _client.SearchUsersAsync(request, cancellationToken: cancellationToken);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error searching users with query: {Query}", query);
            throw;
        }
    }
}

// gRPC 配置和中间件
public static class GrpcServiceExtensions
{
    public static IServiceCollection AddModernGrpcServices(this IServiceCollection services)
    {
        services.AddGrpc(options =>
        {
            options.EnableDetailedErrors = true;
            options.MaxReceiveMessageSize = 4 * 1024 * 1024; // 4MB
            options.MaxSendMessageSize = 4 * 1024 * 1024; // 4MB
        })
        .AddJsonTranscoding()
        .AddServiceOptions<UserGrpcService>(options =>
        {
            options.MaxReceiveMessageSize = 8 * 1024 * 1024; // 8MB
        });
        
        // 添加gRPC反射
        services.AddGrpcReflection();
        
        // 添加gRPC健康检查
        services.AddGrpcHealthChecks();
        
        return services;
    }
    
    public static WebApplication UseModernGrpc(this WebApplication app)
    {
        // 映射gRPC服务
        app.MapGrpcService<UserGrpcService>();
        
        // 映射gRPC健康检查
        app.MapGrpcHealthChecksService();
        
        // 在开发环境中启用gRPC反射
        if (app.Environment.IsDevelopment())
        {
            app.MapGrpcReflectionService();
        }
        
        return app;
    }
}

// 现代API设计模式
public class ModernApiController : ControllerBase
{
    private readonly IMediator _mediator;
    private readonly ILogger<ModernApiController> _logger;
    
    public ModernApiController(IMediator mediator, ILogger<ModernApiController> logger)
    {
        _mediator = mediator;
        _logger = logger;
    }
    
    [HttpGet("/api/v1/users")]
    [ProducesResponseType(typeof(PagedResponse<UserDto>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> GetUsers([FromQuery] GetUsersQuery query, CancellationToken cancellationToken)
    {
        var result = await _mediator.Send(query, cancellationToken);
        return Ok(result);
    }
    
    [HttpGet("/api/v1/users/{id:int}")]
    [ProducesResponseType(typeof(UserDto), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> GetUser(int id, CancellationToken cancellationToken)
    {
        var query = new GetUserQuery { Id = id };
        var result = await _mediator.Send(query, cancellationToken);
        return result != null ? Ok(result) : NotFound();
    }
    
    [HttpPost("/api/v1/users")]
    [ProducesResponseType(typeof(UserDto), StatusCodes.Status201Created)]
    [ProducesResponseType(typeof(ValidationErrorResponse), StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> CreateUser([FromBody] CreateUserCommand command, CancellationToken cancellationToken)
    {
        var result = await _mediator.Send(command, cancellationToken);
        return CreatedAtAction(nameof(GetUser), new { id = result.Id }, result);
    }
    
    [HttpPut("/api/v1/users/{id:int}")]
    [ProducesResponseType(typeof(UserDto), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)]
    [ProducesResponseType(typeof(ValidationErrorResponse), StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> UpdateUser(int id, [FromBody] UpdateUserCommand command, CancellationToken cancellationToken)
    {
        command.Id = id;
        var result = await _mediator.Send(command, cancellationToken);
        return Ok(result);
    }
    
    [HttpDelete("/api/v1/users/{id:int}")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> DeleteUser(int id, CancellationToken cancellationToken)
    {
        var command = new DeleteUserCommand { Id = id };
        await _mediator.Send(command, cancellationToken);
        return NoContent();
    }
}

// 响应模型
public record PagedResponse<T>(IEnumerable<T> Data, int TotalCount, int Page, int PageSize);
public record ErrorResponse(string Message, string? Details = null);
public record ValidationErrorResponse(string Message, Dictionary<string, string[]> Errors);

// CQRS 查询和命令
public record GetUsersQuery : IRequest<PagedResponse<UserDto>>
{
    public int Page { get; init; } = 1;
    public int PageSize { get; init; } = 10;
    public string? Search { get; init; }
    public string? Role { get; init; }
}

public record GetUserQuery : IRequest<UserDto?>
{
    public int Id { get; init; }
}

public record CreateUserCommand : IRequest<UserDto>
{
    public string Name { get; init; } = string.Empty;
    public string Email { get; init; } = string.Empty;
    public string Role { get; init; } = "User";
}

public record UpdateUserCommand : IRequest<UserDto>
{
    public int Id { get; set; }
    public string Name { get; init; } = string.Empty;
    public string Email { get; init; } = string.Empty;
    public string Role { get; init; } = string.Empty;
    public bool IsActive { get; init; }
}

public record DeleteUserCommand : IRequest
{
    public int Id { get; init; }
}

public record UserDto(int Id, string Name, string Email, string Role, bool IsActive, DateTime CreatedAt);

性能优化技术

using System.Buffers;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Extensions.ObjectPool;
using System.Threading.Channels;

// 高性能内存管理
public class HighPerformanceMemoryManager
{
    private readonly ArrayPool<byte> _arrayPool;
    private readonly ObjectPool<StringBuilder> _stringBuilderPool;
    private readonly MemoryPool<byte> _memoryPool;
    
    public HighPerformanceMemoryManager(
        ArrayPool<byte> arrayPool,
        ObjectPool<StringBuilder> stringBuilderPool,
        MemoryPool<byte> memoryPool)
    {
        _arrayPool = arrayPool;
        _stringBuilderPool = stringBuilderPool;
        _memoryPool = memoryPool;
    }
    
    // 使用 ArrayPool 减少内存分配
    public async Task<string> ProcessLargeDataAsync(Stream dataStream)
    {
        var buffer = _arrayPool.Rent(4096);
        try
        {
            var stringBuilder = _stringBuilderPool.Get();
            try
            {
                int bytesRead;
                while ((bytesRead = await dataStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    var text = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    stringBuilder.Append(text.ToUpperInvariant());
                }
                
                return stringBuilder.ToString();
            }
            finally
            {
                _stringBuilderPool.Return(stringBuilder);
            }
        }
        finally
        {
            _arrayPool.Return(buffer);
        }
    }
    
    // 使用 Span<T> 和 Memory<T> 进行零拷贝操作
    public void ProcessDataWithSpan(ReadOnlySpan<byte> data, Span<byte> output)
    {
        for (int i = 0; i < data.Length && i < output.Length; i++)
        {
            output[i] = (byte)(data[i] ^ 0xFF); // 简单的位运算
        }
    }
    
    // 使用 Memory<T> 进行异步操作
    public async Task<Memory<byte>> ReadDataAsync(Stream stream, int length)
    {
        using var memoryOwner = _memoryPool.Rent(length);
        var memory = memoryOwner.Memory[..length];
        
        int totalRead = 0;
        while (totalRead < length)
        {
            var bytesRead = await stream.ReadAsync(memory.Slice(totalRead));
            if (bytesRead == 0) break;
            totalRead += bytesRead;
        }
        
        var result = new byte[totalRead];
        memory[..totalRead].CopyTo(result);
        return result;
    }
}

// 高性能数据处理管道
public class HighPerformanceDataPipeline
{
    private readonly Channel<DataItem> _inputChannel;
    private readonly Channel<ProcessedData> _outputChannel;
    private readonly SemaphoreSlim _processingLimiter;
    
    public HighPerformanceDataPipeline(int maxConcurrency = Environment.ProcessorCount)
    {
        var inputOptions = new BoundedChannelOptions(1000)
        {
            FullMode = BoundedChannelFullMode.Wait,
            SingleReader = false,
            SingleWriter = false
        };
        
        var outputOptions = new BoundedChannelOptions(1000)
        {
            FullMode = BoundedChannelFullMode.Wait,
            SingleReader = true,
            SingleWriter = false
        };
        
        _inputChannel = Channel.CreateBounded<DataItem>(inputOptions);
        _outputChannel = Channel.CreateBounded<ProcessedData>(outputOptions);
        _processingLimiter = new SemaphoreSlim(maxConcurrency, maxConcurrency);
        
        // 启动处理任务
        _ = Task.Run(ProcessDataAsync);
    }
    
    public async Task<bool> AddDataAsync(DataItem item, CancellationToken cancellationToken = default)
    {
        return await _inputChannel.Writer.WaitToWriteAsync(cancellationToken) &&
               _inputChannel.Writer.TryWrite(item);
    }
    
    public async IAsyncEnumerable<ProcessedData> GetProcessedDataAsync(
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        await foreach (var item in _outputChannel.Reader.ReadAllAsync(cancellationToken))
        {
            yield return item;
        }
    }
    
    private async Task ProcessDataAsync()
    {
        await foreach (var item in _inputChannel.Reader.ReadAllAsync())
        {
            await _processingLimiter.WaitAsync();
            
            _ = Task.Run(async () =>
            {
                try
                {
                    var processed = await ProcessSingleItemAsync(item);
                    await _outputChannel.Writer.WriteAsync(processed);
                }
                finally
                {
                    _processingLimiter.Release();
                }
            });
        }
        
        _outputChannel.Writer.Complete();
    }
    
    private async Task<ProcessedData> ProcessSingleItemAsync(DataItem item)
    {
        // 模拟复杂的数据处理
        await Task.Delay(Random.Shared.Next(10, 100));
        
        return new ProcessedData
        {
            Id = item.Id,
            ProcessedValue = item.Value * 2,
            ProcessedAt = DateTime.UtcNow,
            Metadata = $"Processed: {item.Metadata}"
        };
    }
    
    public void Complete()
    {
        _inputChannel.Writer.Complete();
    }
}

// 高性能序列化
public class HighPerformanceSerializer
{
    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        WriteIndented = false
    };
    
    // 使用 System.Text.Json 进行高性能序列化
    public async Task<byte[]> SerializeAsync<T>(T obj)
    {
        using var stream = new MemoryStream();
        await JsonSerializer.SerializeAsync(stream, obj, JsonOptions);
        return stream.ToArray();
    }
    
    public async Task<T?> DeserializeAsync<T>(Stream stream)
    {
        return await JsonSerializer.DeserializeAsync<T>(stream, JsonOptions);
    }
    
    // 使用 Utf8JsonWriter 进行流式写入
    public async Task WriteJsonStreamAsync<T>(IAsyncEnumerable<T> items, Stream output)
    {
        using var writer = new Utf8JsonWriter(output);
        
        writer.WriteStartArray();
        
        await foreach (var item in items)
        {
            JsonSerializer.Serialize(writer, item, JsonOptions);
        }
        
        writer.WriteEndArray();
        await writer.FlushAsync();
    }
    
    // 使用 Utf8JsonReader 进行流式读取
    public async IAsyncEnumerable<T> ReadJsonStreamAsync<T>(Stream input)
    {
        var buffer = new byte[4096];
        var bytesRead = await input.ReadAsync(buffer);
        
        var reader = new Utf8JsonReader(buffer.AsSpan(0, bytesRead));
        
        if (reader.Read() && reader.TokenType == JsonTokenType.StartArray)
        {
            while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
            {
                var item = JsonSerializer.Deserialize<T>(ref reader, JsonOptions);
                if (item != null)
                {
                    yield return item;
                }
            }
        }
    }
}

// 高性能缓存
public class HighPerformanceCache<TKey, TValue> where TKey : notnull
{
    private readonly ConcurrentDictionary<TKey, CacheEntry<TValue>> _cache;
    private readonly Timer _cleanupTimer;
    private readonly TimeSpan _defaultExpiration;
    private readonly int _maxSize;
    
    public HighPerformanceCache(TimeSpan defaultExpiration, int maxSize = 10000)
    {
        _cache = new ConcurrentDictionary<TKey, CacheEntry<TValue>>();
        _defaultExpiration = defaultExpiration;
        _maxSize = maxSize;
        
        // 定期清理过期项
        _cleanupTimer = new Timer(CleanupExpiredItems, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
    }
    
    public bool TryGet(TKey key, out TValue? value)
    {
        if (_cache.TryGetValue(key, out var entry) && !entry.IsExpired)
        {
            entry.LastAccessed = DateTime.UtcNow;
            value = entry.Value;
            return true;
        }
        
        value = default;
        return false;
    }
    
    public void Set(TKey key, TValue value, TimeSpan? expiration = null)
    {
        var expirationTime = expiration ?? _defaultExpiration;
        var entry = new CacheEntry<TValue>
        {
            Value = value,
            ExpiresAt = DateTime.UtcNow.Add(expirationTime),
            LastAccessed = DateTime.UtcNow
        };
        
        _cache.AddOrUpdate(key, entry, (k, oldEntry) => entry);
        
        // 如果缓存大小超过限制,移除最旧的项
        if (_cache.Count > _maxSize)
        {
            RemoveOldestItems();
        }
    }
    
    public async Task<TValue> GetOrSetAsync(TKey key, Func<Task<TValue>> factory, TimeSpan? expiration = null)
    {
        if (TryGet(key, out var value) && value != null)
        {
            return value;
        }
        
        var newValue = await factory();
        Set(key, newValue, expiration);
        return newValue;
    }
    
    private void CleanupExpiredItems(object? state)
    {
        var expiredKeys = _cache
            .Where(kvp => kvp.Value.IsExpired)
            .Select(kvp => kvp.Key)
            .ToList();
        
        foreach (var key in expiredKeys)
        {
            _cache.TryRemove(key, out _);
        }
    }
    
    private void RemoveOldestItems()
    {
        var itemsToRemove = _cache.Count - _maxSize + 100; // 移除额外的100个项以避免频繁清理
        
        var oldestItems = _cache
            .OrderBy(kvp => kvp.Value.LastAccessed)
            .Take(itemsToRemove)
            .Select(kvp => kvp.Key)
            .ToList();
        
        foreach (var key in oldestItems)
        {
            _cache.TryRemove(key, out _);
        }
    }
    
    public void Dispose()
    {
        _cleanupTimer?.Dispose();
    }
}

// 缓存条目
public class CacheEntry<T>
{
    public T Value { get; set; } = default!;
    public DateTime ExpiresAt { get; set; }
    public DateTime LastAccessed { get; set; }
    
    public bool IsExpired => DateTime.UtcNow > ExpiresAt;
}

// 数据模型
public class DataItem
{
    public int Id { get; set; }
    public double Value { get; set; }
    public string Metadata { get; set; } = string.Empty;
    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}

public class ProcessedData
{
    public int Id { get; set; }
    public double ProcessedValue { get; set; }
    public DateTime ProcessedAt { get; set; }
    public string Metadata { get; set; } = string.Empty;
}

// 性能监控
public class PerformanceMonitor
{
    private readonly ILogger<PerformanceMonitor> _logger;
    private readonly ConcurrentDictionary<string, PerformanceMetrics> _metrics;
    
    public PerformanceMonitor(ILogger<PerformanceMonitor> logger)
    {
        _logger = logger;
        _metrics = new ConcurrentDictionary<string, PerformanceMetrics>();
    }
    
    public IDisposable StartOperation(string operationName)
    {
        return new OperationTimer(operationName, this);
    }
    
    internal void RecordOperation(string operationName, TimeSpan duration)
    {
        _metrics.AddOrUpdate(operationName,
            new PerformanceMetrics { Count = 1, TotalDuration = duration, MinDuration = duration, MaxDuration = duration },
            (key, existing) =>
            {
                existing.Count++;
                existing.TotalDuration += duration;
                existing.MinDuration = TimeSpan.FromTicks(Math.Min(existing.MinDuration.Ticks, duration.Ticks));
                existing.MaxDuration = TimeSpan.FromTicks(Math.Max(existing.MaxDuration.Ticks, duration.Ticks));
                return existing;
            });
    }
    
    public void LogMetrics()
    {
        foreach (var kvp in _metrics)
        {
            var metrics = kvp.Value;
            var avgDuration = TimeSpan.FromTicks(metrics.TotalDuration.Ticks / metrics.Count);
            
            _logger.LogInformation(
                "Operation: {Operation}, Count: {Count}, Avg: {AvgDuration}ms, Min: {MinDuration}ms, Max: {MaxDuration}ms",
                kvp.Key, metrics.Count, avgDuration.TotalMilliseconds,
                metrics.MinDuration.TotalMilliseconds, metrics.MaxDuration.TotalMilliseconds);
        }
    }
    
    private class OperationTimer : IDisposable
    {
        private readonly string _operationName;
        private readonly PerformanceMonitor _monitor;
        private readonly Stopwatch _stopwatch;
        
        public OperationTimer(string operationName, PerformanceMonitor monitor)
        {
            _operationName = operationName;
            _monitor = monitor;
            _stopwatch = Stopwatch.StartNew();
        }
        
        public void Dispose()
        {
            _stopwatch.Stop();
            _monitor.RecordOperation(_operationName, _stopwatch.Elapsed);
        }
    }
}

public class PerformanceMetrics
{
    public long Count { get; set; }
    public TimeSpan TotalDuration { get; set; }
    public TimeSpan MinDuration { get; set; }
    public TimeSpan MaxDuration { get; set; }
}

新兴应用领域

区块链和 Web3 开发

using System.Security.Cryptography;
using System.Text.Json;
using Nethereum.Web3;
using Nethereum.Web3.Accounts;
using Nethereum.Contracts;
using Nethereum.Hex.HexTypes;

// 简单区块链实现
public class SimpleBlockchain
{
    private readonly List<Block> _chain;
    private readonly List<Transaction> _pendingTransactions;
    private readonly int _miningReward;
    
    public SimpleBlockchain()
    {
        _chain = new List<Block> { CreateGenesisBlock() };
        _pendingTransactions = new List<Transaction>();
        _miningReward = 100;
    }
    
    private Block CreateGenesisBlock()
    {
        return new Block(DateTime.UtcNow, new List<Transaction>(), "0")
        {
            Hash = "0"
        };
    }
    
    public Block GetLatestBlock()
    {
        return _chain[^1];
    }
    
    public void CreateTransaction(Transaction transaction)
    {
        if (!IsValidTransaction(transaction))
        {
            throw new InvalidOperationException("Invalid transaction");
        }
        
        _pendingTransactions.Add(transaction);
    }
    
    public void MinePendingTransactions(string miningRewardAddress)
    {
        // 添加挖矿奖励交易
        var rewardTransaction = new Transaction(null, miningRewardAddress, _miningReward);
        _pendingTransactions.Add(rewardTransaction);
        
        var block = new Block(
            DateTime.UtcNow,
            _pendingTransactions.ToList(),
            GetLatestBlock().Hash);
        
        block.MineBlock(4); // 难度为4
        
        _chain.Add(block);
        _pendingTransactions.Clear();
    }
    
    public decimal GetBalance(string address)
    {
        decimal balance = 0;
        
        foreach (var block in _chain)
        {
            foreach (var transaction in block.Transactions)
            {
                if (transaction.FromAddress == address)
                {
                    balance -= transaction.Amount;
                }
                
                if (transaction.ToAddress == address)
                {
                    balance += transaction.Amount;
                }
            }
        }
        
        return balance;
    }
    
    public bool IsChainValid()
    {
        for (int i = 1; i < _chain.Count; i++)
        {
            var currentBlock = _chain[i];
            var previousBlock = _chain[i - 1];
            
            if (currentBlock.Hash != currentBlock.CalculateHash())
            {
                return false;
            }
            
            if (currentBlock.PreviousHash != previousBlock.Hash)
            {
                return false;
            }
        }
        
        return true;
    }
    
    private bool IsValidTransaction(Transaction transaction)
    {
        if (transaction.FromAddress == null) return true; // 挖矿奖励
        
        if (string.IsNullOrEmpty(transaction.Signature))
        {
            return false;
        }
        
        var balance = GetBalance(transaction.FromAddress);
        return balance >= transaction.Amount;
    }
}

// 区块
public class Block
{
    public DateTime Timestamp { get; set; }
    public List<Transaction> Transactions { get; set; }
    public string PreviousHash { get; set; }
    public string Hash { get; set; }
    public int Nonce { get; set; }
    
    public Block(DateTime timestamp, List<Transaction> transactions, string previousHash)
    {
        Timestamp = timestamp;
        Transactions = transactions;
        PreviousHash = previousHash;
        Hash = CalculateHash();
        Nonce = 0;
    }
    
    public string CalculateHash()
    {
        var data = $"{PreviousHash}{Timestamp:O}{JsonSerializer.Serialize(Transactions)}{Nonce}";
        using var sha256 = SHA256.Create();
        var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(data));
        return Convert.ToHexString(hashBytes);
    }
    
    public void MineBlock(int difficulty)
    {
        var target = new string('0', difficulty);
        
        while (Hash[..difficulty] != target)
        {
            Nonce++;
            Hash = CalculateHash();
        }
        
        Console.WriteLine($"Block mined: {Hash}");
    }
}

// 交易
public class Transaction
{
    public string? FromAddress { get; set; }
    public string ToAddress { get; set; }
    public decimal Amount { get; set; }
    public DateTime Timestamp { get; set; }
    public string Signature { get; set; } = string.Empty;
    
    public Transaction(string? fromAddress, string toAddress, decimal amount)
    {
        FromAddress = fromAddress;
        ToAddress = toAddress;
        Amount = amount;
        Timestamp = DateTime.UtcNow;
    }
    
    public string CalculateHash()
    {
        var data = $"{FromAddress}{ToAddress}{Amount}{Timestamp:O}";
        using var sha256 = SHA256.Create();
        var hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(data));
        return Convert.ToHexString(hashBytes);
    }
    
    public void SignTransaction(string privateKey)
    {
        // 简化的签名实现
        var hash = CalculateHash();
        Signature = $"{privateKey}:{hash}";
    }
    
    public bool IsValid()
    {
        if (FromAddress == null) return true; // 挖矿奖励
        
        if (string.IsNullOrEmpty(Signature))
        {
            return false;
        }
        
        // 简化的签名验证
        var parts = Signature.Split(':');
        if (parts.Length != 2) return false;
        
        var expectedHash = CalculateHash();
        return parts[1] == expectedHash;
    }
}

// 以太坊智能合约交互
public class EthereumContractService
{
    private readonly Web3 _web3;
    private readonly Account _account;
    
    public EthereumContractService(string nodeUrl, string privateKey)
    {
        _account = new Account(privateKey);
        _web3 = new Web3(_account, nodeUrl);
    }
    
    public async Task<string> DeployContractAsync(string contractBytecode, string abi, params object[] constructorParams)
    {
        try
        {
            var deployment = new ContractDeploymentMessage
            {
                Bytecode = contractBytecode,
                Gas = new HexBigInteger(3000000),
                GasPrice = new HexBigInteger(20000000000) // 20 Gwei
            };
            
            var receipt = await _web3.Eth.DeployContract.SendRequestAndWaitForReceiptAsync(deployment);
            return receipt.ContractAddress;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Contract deployment failed: {ex.Message}", ex);
        }
    }
    
    public async Task<T> CallContractFunctionAsync<T>(string contractAddress, string abi, string functionName, params object[] parameters)
    {
        try
        {
            var contract = _web3.Eth.GetContract(abi, contractAddress);
            var function = contract.GetFunction(functionName);
            
            return await function.CallAsync<T>(parameters);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Contract function call failed: {ex.Message}", ex);
        }
    }
    
    public async Task<string> SendContractTransactionAsync(string contractAddress, string abi, string functionName, params object[] parameters)
    {
        try
        {
            var contract = _web3.Eth.GetContract(abi, contractAddress);
            var function = contract.GetFunction(functionName);
            
            var gas = await function.EstimateGasAsync(_account.Address, null, null, parameters);
            var receipt = await function.SendTransactionAndWaitForReceiptAsync(
                _account.Address, gas, null, null, parameters);
            
            return receipt.TransactionHash;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Contract transaction failed: {ex.Message}", ex);
        }
    }
    
    public async Task<decimal> GetBalanceAsync(string address)
    {
        var balance = await _web3.Eth.GetBalance.SendRequestAsync(address);
        return Web3.Convert.FromWei(balance.Value);
    }
    
    public async Task<string> SendEtherAsync(string toAddress, decimal amount)
    {
        try
        {
            var amountInWei = Web3.Convert.ToWei(amount);
            var transaction = await _web3.Eth.GetEtherTransferService()
                .TransferEtherAndWaitForReceiptAsync(toAddress, amount);
            
            return transaction.TransactionHash;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Ether transfer failed: {ex.Message}", ex);
        }
    }
}

// NFT 管理
public class NFTManager
{
    private readonly EthereumContractService _contractService;
    private readonly string _nftContractAddress;
    private readonly string _nftContractAbi;
    
    public NFTManager(EthereumContractService contractService, string nftContractAddress, string nftContractAbi)
    {
        _contractService = contractService;
        _nftContractAddress = nftContractAddress;
        _nftContractAbi = nftContractAbi;
    }
    
    public async Task<string> MintNFTAsync(string toAddress, string tokenURI, Dictionary<string, object> metadata)
    {
        try
        {
            // 上传元数据到IPFS或其他存储
            var metadataUri = await UploadMetadataAsync(metadata);
            
            // 调用智能合约的mint函数
            var transactionHash = await _contractService.SendContractTransactionAsync(
                _nftContractAddress,
                _nftContractAbi,
                "mint",
                toAddress,
                metadataUri
            );
            
            return transactionHash;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"NFT minting failed: {ex.Message}", ex);
        }
    }
    
    public async Task<NFTMetadata> GetNFTMetadataAsync(int tokenId)
    {
        try
        {
            var tokenURI = await _contractService.CallContractFunctionAsync<string>(
                _nftContractAddress,
                _nftContractAbi,
                "tokenURI",
                tokenId
            );
            
            // 从IPFS或其他存储获取元数据
            return await FetchMetadataAsync(tokenURI);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Failed to get NFT metadata: {ex.Message}", ex);
        }
    }
    
    public async Task<string> TransferNFTAsync(string fromAddress, string toAddress, int tokenId)
    {
        try
        {
            var transactionHash = await _contractService.SendContractTransactionAsync(
                _nftContractAddress,
                _nftContractAbi,
                "transferFrom",
                fromAddress,
                toAddress,
                tokenId
            );
            
            return transactionHash;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"NFT transfer failed: {ex.Message}", ex);
        }
    }
    
    public async Task<List<int>> GetOwnedTokensAsync(string ownerAddress)
    {
        try
        {
            var balance = await _contractService.CallContractFunctionAsync<int>(
                _nftContractAddress,
                _nftContractAbi,
                "balanceOf",
                ownerAddress
            );
            
            var tokens = new List<int>();
            for (int i = 0; i < balance; i++)
            {
                var tokenId = await _contractService.CallContractFunctionAsync<int>(
                    _nftContractAddress,
                    _nftContractAbi,
                    "tokenOfOwnerByIndex",
                    ownerAddress,
                    i
                );
                tokens.Add(tokenId);
            }
            
            return tokens;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Failed to get owned tokens: {ex.Message}", ex);
        }
    }
    
    private async Task<string> UploadMetadataAsync(Dictionary<string, object> metadata)
    {
        // 简化实现 - 实际应用中应该上传到IPFS
        var json = JsonSerializer.Serialize(metadata);
        var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(json)));
        return $"ipfs://{hash}";
    }
    
    private async Task<NFTMetadata> FetchMetadataAsync(string tokenURI)
    {
        // 简化实现 - 实际应用中应该从IPFS获取
        return new NFTMetadata
        {
            Name = "Sample NFT",
            Description = "A sample NFT",
            Image = "ipfs://sample-image-hash",
            Attributes = new List<NFTAttribute>
            {
                new() { TraitType = "Color", Value = "Blue" },
                new() { TraitType = "Rarity", Value = "Common" }
            }
        };
    }
}

// NFT 元数据模型
public class NFTMetadata
{
    public string Name { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public string Image { get; set; } = string.Empty;
    public List<NFTAttribute> Attributes { get; set; } = new();
}

public class NFTAttribute
{
    public string TraitType { get; set; } = string.Empty;
    public string Value { get; set; } = string.Empty;
    public string? DisplayType { get; set; }
}

// DeFi 协议交互
public class DeFiProtocolService
{
    private readonly EthereumContractService _contractService;
    
    public DeFiProtocolService(EthereumContractService contractService)
    {
        _contractService = contractService;
    }
    
    public async Task<string> SwapTokensAsync(string dexContractAddress, string dexAbi, 
        string tokenA, string tokenB, decimal amountIn, decimal minAmountOut)
    {
        try
        {
            var transactionHash = await _contractService.SendContractTransactionAsync(
                dexContractAddress,
                dexAbi,
                "swapExactTokensForTokens",
                Web3.Convert.ToWei(amountIn),
                Web3.Convert.ToWei(minAmountOut),
                new[] { tokenA, tokenB },
                _contractService._account.Address,
                DateTimeOffset.UtcNow.AddMinutes(20).ToUnixTimeSeconds()
            );
            
            return transactionHash;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Token swap failed: {ex.Message}", ex);
        }
    }
    
    public async Task<string> ProvideLiquidityAsync(string poolContractAddress, string poolAbi,
        string tokenA, string tokenB, decimal amountA, decimal amountB)
    {
        try
        {
            var transactionHash = await _contractService.SendContractTransactionAsync(
                poolContractAddress,
                poolAbi,
                "addLiquidity",
                tokenA,
                tokenB,
                Web3.Convert.ToWei(amountA),
                Web3.Convert.ToWei(amountB),
                Web3.Convert.ToWei(amountA * 0.95m), // 5% slippage
                Web3.Convert.ToWei(amountB * 0.95m),
                _contractService._account.Address,
                DateTimeOffset.UtcNow.AddMinutes(20).ToUnixTimeSeconds()
            );
            
            return transactionHash;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Liquidity provision failed: {ex.Message}", ex);
        }
     }
 }

量子计算应用

using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
using System.Numerics;

// 量子计算模拟器
public class QuantumComputingSimulator
{
    private readonly QuantumSimulator _simulator;
    
    public QuantumComputingSimulator()
    {
        _simulator = new QuantumSimulator();
    }
    
    // 量子随机数生成
    public async Task<bool[]> GenerateQuantumRandomBitsAsync(int count)
    {
        var results = new bool[count];
        
        for (int i = 0; i < count; i++)
        {
            // 模拟量子随机数生成
            results[i] = await SimulateQuantumRandomBitAsync();
        }
        
        return results;
    }
    
    private async Task<bool> SimulateQuantumRandomBitAsync()
    {
        // 简化的量子随机数生成模拟
        // 在真实的量子计算中,这将使用量子叠加态
        var random = new Random();
        await Task.Delay(1); // 模拟量子操作时间
        return random.NextDouble() > 0.5;
    }
    
    // 量子加密密钥生成
    public async Task<QuantumKey> GenerateQuantumKeyAsync(int keyLength)
    {
        var keyBits = await GenerateQuantumRandomBitsAsync(keyLength);
        var key = new QuantumKey
        {
            Bits = keyBits,
            Length = keyLength,
            GeneratedAt = DateTime.UtcNow,
            Entropy = CalculateEntropy(keyBits)
        };
        
        return key;
    }
    
    // 量子纠缠模拟
    public async Task<QuantumEntanglementResult> SimulateQuantumEntanglementAsync()
    {
        // 模拟量子纠缠对的创建和测量
        var entangledPair = await CreateEntangledPairAsync();
        
        // 测量第一个量子比特
        var measurement1 = await MeasureQuantumBitAsync(entangledPair.Qubit1);
        
        // 由于纠缠,第二个量子比特的测量结果应该是相关的
        var measurement2 = await MeasureQuantumBitAsync(entangledPair.Qubit2);
        
        return new QuantumEntanglementResult
        {
            Measurement1 = measurement1,
            Measurement2 = measurement2,
            IsEntangled = measurement1.Value != measurement2.Value, // 简化的纠缠验证
            CorrelationStrength = CalculateCorrelation(measurement1, measurement2)
        };
    }
    
    // 量子算法模拟 - Grover搜索算法
    public async Task<GroverSearchResult> SimulateGroverSearchAsync(int[] searchSpace, int target)
    {
        var startTime = DateTime.UtcNow;
        
        // 模拟Grover算法的量子搜索
        var iterations = (int)Math.Ceiling(Math.PI / 4 * Math.Sqrt(searchSpace.Length));
        
        for (int i = 0; i < iterations; i++)
        {
            // 模拟量子叠加和振幅放大
            await Task.Delay(10); // 模拟量子操作
        }
        
        var endTime = DateTime.UtcNow;
        var foundIndex = Array.IndexOf(searchSpace, target);
        
        return new GroverSearchResult
        {
            Target = target,
            FoundIndex = foundIndex,
            Found = foundIndex >= 0,
            Iterations = iterations,
            ClassicalIterations = searchSpace.Length / 2, // 平均情况
            QuantumSpeedup = foundIndex >= 0 ? (double)(searchSpace.Length / 2) / iterations : 0,
            ExecutionTime = endTime - startTime
        };
    }
    
    // 量子机器学习模拟
    public async Task<QuantumMLResult> SimulateQuantumMachineLearningAsync(double[][] trainingData, double[] labels)
    {
        var startTime = DateTime.UtcNow;
        
        // 模拟量子特征映射
        var quantumFeatures = await MapToQuantumFeaturesAsync(trainingData);
        
        // 模拟变分量子分类器训练
        var model = await TrainVariationalQuantumClassifierAsync(quantumFeatures, labels);
        
        var endTime = DateTime.UtcNow;
        
        return new QuantumMLResult
        {
            Model = model,
            TrainingTime = endTime - startTime,
            QuantumAdvantage = CalculateQuantumAdvantage(trainingData.Length),
            Accuracy = await EvaluateModelAsync(model, quantumFeatures, labels)
        };
    }
    
    private async Task<QuantumEntangledPair> CreateEntangledPairAsync()
    {
        await Task.Delay(5); // 模拟量子纠缠创建时间
        
        return new QuantumEntangledPair
        {
            Qubit1 = new QuantumBit { Id = Guid.NewGuid(), State = QuantumState.Superposition },
            Qubit2 = new QuantumBit { Id = Guid.NewGuid(), State = QuantumState.Superposition },
            EntanglementStrength = 1.0
        };
    }
    
    private async Task<QuantumMeasurement> MeasureQuantumBitAsync(QuantumBit qubit)
    {
        await Task.Delay(1); // 模拟测量时间
        
        var random = new Random();
        var value = random.NextDouble() > 0.5;
        
        return new QuantumMeasurement
        {
            QubitId = qubit.Id,
            Value = value,
            Probability = 0.5, // 在叠加态中,测量概率为50%
            MeasuredAt = DateTime.UtcNow
        };
    }
    
    private double CalculateEntropy(bool[] bits)
    {
        var ones = bits.Count(b => b);
        var zeros = bits.Length - ones;
        
        if (ones == 0 || zeros == 0) return 0;
        
        var p1 = (double)ones / bits.Length;
        var p0 = (double)zeros / bits.Length;
        
        return -(p1 * Math.Log2(p1) + p0 * Math.Log2(p0));
    }
    
    private double CalculateCorrelation(QuantumMeasurement m1, QuantumMeasurement m2)
    {
        // 简化的相关性计算
        return m1.Value == m2.Value ? -1.0 : 1.0; // 反相关表示纠缠
    }
    
    private async Task<double[][]> MapToQuantumFeaturesAsync(double[][] classicalData)
    {
        // 模拟量子特征映射
        var quantumFeatures = new double[classicalData.Length][];
        
        for (int i = 0; i < classicalData.Length; i++)
        {
            quantumFeatures[i] = new double[classicalData[i].Length * 2]; // 量子特征空间扩展
            
            for (int j = 0; j < classicalData[i].Length; j++)
            {
                // 模拟量子特征映射 φ(x) = [cos(πx), sin(πx)]
                quantumFeatures[i][j * 2] = Math.Cos(Math.PI * classicalData[i][j]);
                quantumFeatures[i][j * 2 + 1] = Math.Sin(Math.PI * classicalData[i][j]);
            }
            
            await Task.Delay(1); // 模拟量子映射时间
        }
        
        return quantumFeatures;
    }
    
    private async Task<QuantumMLModel> TrainVariationalQuantumClassifierAsync(double[][] features, double[] labels)
    {
        // 模拟变分量子分类器训练
        var parameters = new double[features[0].Length];
        var random = new Random();
        
        // 初始化随机参数
        for (int i = 0; i < parameters.Length; i++)
        {
            parameters[i] = random.NextDouble() * 2 * Math.PI;
        }
        
        // 模拟训练迭代
        for (int epoch = 0; epoch < 100; epoch++)
        {
            // 模拟梯度计算和参数更新
            for (int i = 0; i < parameters.Length; i++)
            {
                parameters[i] += (random.NextDouble() - 0.5) * 0.01; // 简化的参数更新
            }
            
            await Task.Delay(1); // 模拟训练时间
        }
        
        return new QuantumMLModel
        {
            Parameters = parameters,
            FeatureDimension = features[0].Length,
            TrainedAt = DateTime.UtcNow
        };
    }
    
    private async Task<double> EvaluateModelAsync(QuantumMLModel model, double[][] features, double[] labels)
    {
        int correct = 0;
        
        for (int i = 0; i < features.Length; i++)
        {
            var prediction = await PredictAsync(model, features[i]);
            if (Math.Round(prediction) == labels[i])
            {
                correct++;
            }
        }
        
        return (double)correct / features.Length;
    }
    
    private async Task<double> PredictAsync(QuantumMLModel model, double[] features)
    {
        // 模拟量子预测
        double result = 0;
        
        for (int i = 0; i < features.Length; i++)
        {
            result += features[i] * Math.Cos(model.Parameters[i]);
        }
        
        await Task.Delay(1); // 模拟预测时间
        
        return Math.Sigmoid(result); // 使用Sigmoid激活函数
    }
    
    private double CalculateQuantumAdvantage(int dataSize)
    {
        // 简化的量子优势计算
        return Math.Log2(dataSize); // 量子算法通常提供多项式或指数级加速
    }
    
    public void Dispose()
    {
        _simulator?.Dispose();
    }
}

// 量子计算相关数据模型
public class QuantumKey
{
    public bool[] Bits { get; set; } = Array.Empty<bool>();
    public int Length { get; set; }
    public DateTime GeneratedAt { get; set; }
    public double Entropy { get; set; }
}

public class QuantumBit
{
    public Guid Id { get; set; }
    public QuantumState State { get; set; }
}

public enum QuantumState
{
    Zero,
    One,
    Superposition
}

public class QuantumEntangledPair
{
    public QuantumBit Qubit1 { get; set; } = new();
    public QuantumBit Qubit2 { get; set; } = new();
    public double EntanglementStrength { get; set; }
}

public class QuantumMeasurement
{
    public Guid QubitId { get; set; }
    public bool Value { get; set; }
    public double Probability { get; set; }
    public DateTime MeasuredAt { get; set; }
}

public class QuantumEntanglementResult
{
    public QuantumMeasurement Measurement1 { get; set; } = new();
    public QuantumMeasurement Measurement2 { get; set; } = new();
    public bool IsEntangled { get; set; }
    public double CorrelationStrength { get; set; }
}

public class GroverSearchResult
{
    public int Target { get; set; }
    public int FoundIndex { get; set; }
    public bool Found { get; set; }
    public int Iterations { get; set; }
    public int ClassicalIterations { get; set; }
    public double QuantumSpeedup { get; set; }
    public TimeSpan ExecutionTime { get; set; }
}

public class QuantumMLModel
{
    public double[] Parameters { get; set; } = Array.Empty<double>();
    public int FeatureDimension { get; set; }
    public DateTime TrainedAt { get; set; }
}

public class QuantumMLResult
{
    public QuantumMLModel Model { get; set; } = new();
    public TimeSpan TrainingTime { get; set; }
    public double QuantumAdvantage { get; set; }
    public double Accuracy { get; set; }
}

// 数学扩展方法
public static class MathExtensions
{
    public static double Sigmoid(double x)
    {
        return 1.0 / (1.0 + Math.Exp(-x));
    }
}

AR/VR 应用开发

using System.Numerics;
using Microsoft.Extensions.Logging;

// AR/VR 应用框架
public class ARVRApplicationFramework
{
    private readonly ILogger<ARVRApplicationFramework> _logger;
    private readonly List<ARObject> _arObjects;
    private readonly List<VRObject> _vrObjects;
    private readonly SpatialTracker _spatialTracker;
    
    public ARVRApplicationFramework(ILogger<ARVRApplicationFramework> logger)
    {
        _logger = logger;
        _arObjects = new List<ARObject>();
        _vrObjects = new List<VRObject>();
        _spatialTracker = new SpatialTracker();
    }
    
    // AR 对象管理
    public void AddARObject(ARObject arObject)
    {
        arObject.Id = Guid.NewGuid();
        arObject.CreatedAt = DateTime.UtcNow;
        _arObjects.Add(arObject);
        
        _logger.LogInformation("AR object added: {ObjectId} at position {Position}", 
            arObject.Id, arObject.Position);
    }
    
    public void UpdateARObject(Guid objectId, Vector3 newPosition, Quaternion newRotation)
    {
        var arObject = _arObjects.FirstOrDefault(obj => obj.Id == objectId);
        if (arObject != null)
        {
            arObject.Position = newPosition;
            arObject.Rotation = newRotation;
            arObject.LastUpdated = DateTime.UtcNow;
            
            _logger.LogDebug("AR object updated: {ObjectId}", objectId);
        }
    }
    
    public void RemoveARObject(Guid objectId)
    {
        var arObject = _arObjects.FirstOrDefault(obj => obj.Id == objectId);
        if (arObject != null)
        {
            _arObjects.Remove(arObject);
            _logger.LogInformation("AR object removed: {ObjectId}", objectId);
        }
    }
    
    // 空间追踪和映射
    public async Task<SpatialMap> CreateSpatialMapAsync()
    {
        _logger.LogInformation("Starting spatial mapping...");
        
        var spatialMap = new SpatialMap
        {
            Id = Guid.NewGuid(),
            CreatedAt = DateTime.UtcNow,
            Surfaces = new List<SpatialSurface>(),
            Anchors = new List<SpatialAnchor>()
        };
        
        // 模拟空间扫描过程
        for (int i = 0; i < 10; i++)
        {
            await Task.Delay(100); // 模拟扫描时间
            
            var surface = await _spatialTracker.ScanSurfaceAsync();
            spatialMap.Surfaces.Add(surface);
            
            _logger.LogDebug("Surface scanned: {SurfaceId}", surface.Id);
        }
        
        _logger.LogInformation("Spatial mapping completed. Found {SurfaceCount} surfaces", 
            spatialMap.Surfaces.Count);
        
        return spatialMap;
    }
    
    // 手势识别
    public async Task<GestureRecognitionResult> RecognizeGestureAsync(HandTrackingData handData)
    {
        var gestureRecognizer = new GestureRecognizer();
        
        var result = await gestureRecognizer.RecognizeAsync(handData);
        
        if (result.Confidence > 0.8)
        {
            _logger.LogInformation("Gesture recognized: {GestureType} with confidence {Confidence}", 
                result.GestureType, result.Confidence);
            
            // 触发手势事件
            await HandleGestureAsync(result);
        }
        
        return result;
    }
    
    // VR 环境管理
    public async Task<VREnvironment> CreateVREnvironmentAsync(VREnvironmentConfig config)
    {
        _logger.LogInformation("Creating VR environment: {EnvironmentName}", config.Name);
        
        var environment = new VREnvironment
        {
            Id = Guid.NewGuid(),
            Name = config.Name,
            CreatedAt = DateTime.UtcNow,
            Objects = new List<VRObject>(),
            Lighting = config.Lighting,
            Physics = new PhysicsEngine()
        };
        
        // 加载环境资源
        await LoadEnvironmentAssetsAsync(environment, config);
        
        // 初始化物理引擎
        environment.Physics.Initialize(config.Gravity, config.CollisionDetection);
        
        _logger.LogInformation("VR environment created successfully");
        
        return environment;
    }
    
    // 多用户协作
    public async Task<CollaborativeSession> StartCollaborativeSessionAsync(string sessionName)
    {
        var session = new CollaborativeSession
        {
            Id = Guid.NewGuid(),
            Name = sessionName,
            CreatedAt = DateTime.UtcNow,
            Participants = new List<Participant>(),
            SharedObjects = new List<SharedObject>()
        };
        
        _logger.LogInformation("Collaborative session started: {SessionId}", session.Id);
        
        return session;
    }
    
    public async Task AddParticipantAsync(CollaborativeSession session, User user)
    {
        var participant = new Participant
        {
            Id = Guid.NewGuid(),
            UserId = user.Id,
            UserName = user.Name,
            JoinedAt = DateTime.UtcNow,
            Avatar = await CreateAvatarAsync(user),
            Position = Vector3.Zero,
            Rotation = Quaternion.Identity
        };
        
        session.Participants.Add(participant);
        
        _logger.LogInformation("Participant added to session: {UserId}", user.Id);
        
        // 通知其他参与者
        await NotifyParticipantsAsync(session, $"{user.Name} joined the session");
    }
    
    // 实时渲染优化
    public async Task OptimizeRenderingAsync(RenderingContext context)
    {
        // 视锥剔除
        var visibleObjects = PerformFrustumCulling(context.Camera, _arObjects.Cast<IRenderable>().ToList());
        
        // LOD (Level of Detail) 管理
        foreach (var obj in visibleObjects)
        {
            var distance = Vector3.Distance(context.Camera.Position, obj.Position);
            obj.LevelOfDetail = CalculateLOD(distance);
        }
        
        // 批处理渲染
        var batches = GroupObjectsForBatching(visibleObjects);
        
        foreach (var batch in batches)
        {
            await RenderBatchAsync(batch, context);
        }
        
        _logger.LogDebug("Rendered {ObjectCount} objects in {BatchCount} batches", 
            visibleObjects.Count, batches.Count);
    }
    
    private async Task HandleGestureAsync(GestureRecognitionResult gesture)
    {
        switch (gesture.GestureType)
        {
            case GestureType.Tap:
                await HandleTapGestureAsync(gesture);
                break;
            case GestureType.Pinch:
                await HandlePinchGestureAsync(gesture);
                break;
            case GestureType.Swipe:
                await HandleSwipeGestureAsync(gesture);
                break;
            default:
                _logger.LogWarning("Unknown gesture type: {GestureType}", gesture.GestureType);
                break;
        }
    }
    
    private async Task HandleTapGestureAsync(GestureRecognitionResult gesture)
    {
        // 射线检测
        var ray = new Ray(gesture.Position, gesture.Direction);
        var hitObject = PerformRaycast(ray);
        
        if (hitObject != null)
        {
            await hitObject.OnTapAsync(gesture.Position);
            _logger.LogInformation("Object tapped: {ObjectId}", hitObject.Id);
        }
    }
    
    private async Task HandlePinchGestureAsync(GestureRecognitionResult gesture)
    {
        // 实现捏取手势逻辑
        var selectedObject = GetSelectedObject();
        if (selectedObject != null)
        {
            selectedObject.Scale *= gesture.PinchStrength;
            await selectedObject.UpdateAsync();
        }
    }
    
    private async Task HandleSwipeGestureAsync(GestureRecognitionResult gesture)
    {
        // 实现滑动手势逻辑
        var swipeDirection = gesture.Direction;
        await NavigateBasedOnSwipeAsync(swipeDirection);
    }
    
    private async Task LoadEnvironmentAssetsAsync(VREnvironment environment, VREnvironmentConfig config)
    {
        foreach (var assetPath in config.AssetPaths)
        {
            var asset = await LoadAssetAsync(assetPath);
            environment.Objects.Add(asset);
        }
    }
    
    private async Task<VRObject> LoadAssetAsync(string assetPath)
    {
        // 模拟资源加载
        await Task.Delay(100);
        
        return new VRObject
        {
            Id = Guid.NewGuid(),
            Name = Path.GetFileNameWithoutExtension(assetPath),
            AssetPath = assetPath,
            Position = Vector3.Zero,
            Rotation = Quaternion.Identity,
            Scale = Vector3.One
        };
    }
    
    private async Task<Avatar> CreateAvatarAsync(User user)
    {
        return new Avatar
        {
            Id = Guid.NewGuid(),
            UserId = user.Id,
            Name = user.Name,
            ModelPath = $"avatars/{user.Id}.fbx",
            Position = Vector3.Zero,
            Rotation = Quaternion.Identity
        };
    }
    
    private async Task NotifyParticipantsAsync(CollaborativeSession session, string message)
    {
        foreach (var participant in session.Participants)
        {
            // 发送通知给参与者
            await SendNotificationAsync(participant.UserId, message);
        }
    }
    
    private async Task SendNotificationAsync(Guid userId, string message)
    {
        // 实现通知发送逻辑
        _logger.LogInformation("Notification sent to user {UserId}: {Message}", userId, message);
        await Task.CompletedTask;
    }
    
    private List<IRenderable> PerformFrustumCulling(Camera camera, List<IRenderable> objects)
    {
        return objects.Where(obj => IsInFrustum(camera, obj)).ToList();
    }
    
    private bool IsInFrustum(Camera camera, IRenderable obj)
    {
        // 简化的视锥剔除检测
        var distance = Vector3.Distance(camera.Position, obj.Position);
        return distance <= camera.FarPlane;
    }
    
    private int CalculateLOD(float distance)
    {
        if (distance < 10) return 0; // 高细节
        if (distance < 50) return 1; // 中等细节
        return 2; // 低细节
    }
    
    private List<RenderBatch> GroupObjectsForBatching(List<IRenderable> objects)
    {
        return objects
            .GroupBy(obj => obj.MaterialId)
            .Select(group => new RenderBatch
            {
                MaterialId = group.Key,
                Objects = group.ToList()
            })
            .ToList();
    }
    
    private async Task RenderBatchAsync(RenderBatch batch, RenderingContext context)
    {
        // 实现批处理渲染逻辑
        await Task.Delay(1); // 模拟渲染时间
    }
    
    private IRenderable? PerformRaycast(Ray ray)
    {
        // 简化的射线检测
        return _arObjects.Cast<IRenderable>()
            .FirstOrDefault(obj => IsRayIntersecting(ray, obj));
    }
    
    private bool IsRayIntersecting(Ray ray, IRenderable obj)
    {
        // 简化的射线-对象相交检测
        var distance = Vector3.Distance(ray.Origin, obj.Position);
        return distance < 1.0f; // 简单的距离检测
    }
    
    private IRenderable? GetSelectedObject()
    {
        // 返回当前选中的对象
        return _arObjects.Cast<IRenderable>().FirstOrDefault();
    }
    
    private async Task NavigateBasedOnSwipeAsync(Vector3 swipeDirection)
     {
         // 实现基于滑动的导航逻辑
         _logger.LogInformation("Navigating based on swipe direction: {Direction}", swipeDirection);
         await Task.CompletedTask;
     }
 }

 // AR/VR 相关数据模型
 public class ARObject : IRenderable
 {
     public Guid Id { get; set; }
     public string Name { get; set; } = string.Empty;
     public Vector3 Position { get; set; }
     public Quaternion Rotation { get; set; }
     public Vector3 Scale { get; set; } = Vector3.One;
     public DateTime CreatedAt { get; set; }
     public DateTime LastUpdated { get; set; }
     public string MaterialId { get; set; } = string.Empty;
     public int LevelOfDetail { get; set; }
     
     public async Task OnTapAsync(Vector3 tapPosition)
     {
         // 处理点击事件
         await Task.CompletedTask;
     }
     
     public async Task UpdateAsync()
     {
         LastUpdated = DateTime.UtcNow;
         await Task.CompletedTask;
     }
 }
 
 public class VRObject
 {
     public Guid Id { get; set; }
     public string Name { get; set; } = string.Empty;
     public string AssetPath { get; set; } = string.Empty;
     public Vector3 Position { get; set; }
     public Quaternion Rotation { get; set; }
     public Vector3 Scale { get; set; } = Vector3.One;
 }
 
 public interface IRenderable
 {
     Guid Id { get; set; }
     Vector3 Position { get; set; }
     string MaterialId { get; set; }
     int LevelOfDetail { get; set; }
 }
 
 public class SpatialTracker
 {
     public async Task<SpatialSurface> ScanSurfaceAsync()
     {
         await Task.Delay(50); // 模拟扫描时间
         
         return new SpatialSurface
         {
             Id = Guid.NewGuid(),
             Vertices = GenerateRandomVertices(),
             Normal = Vector3.UnitY,
             Area = 1.0f
         };
     }
     
     private Vector3[] GenerateRandomVertices()
     {
         var random = new Random();
         var vertices = new Vector3[4];
         
         for (int i = 0; i < vertices.Length; i++)
         {
             vertices[i] = new Vector3(
                 (float)(random.NextDouble() * 10 - 5),
                 0,
                 (float)(random.NextDouble() * 10 - 5)
             );
         }
         
         return vertices;
     }
 }
 
 public class SpatialMap
 {
     public Guid Id { get; set; }
     public DateTime CreatedAt { get; set; }
     public List<SpatialSurface> Surfaces { get; set; } = new();
     public List<SpatialAnchor> Anchors { get; set; } = new();
 }
 
 public class SpatialSurface
 {
     public Guid Id { get; set; }
     public Vector3[] Vertices { get; set; } = Array.Empty<Vector3>();
     public Vector3 Normal { get; set; }
     public float Area { get; set; }
 }
 
 public class SpatialAnchor
 {
     public Guid Id { get; set; }
     public Vector3 Position { get; set; }
     public Quaternion Rotation { get; set; }
     public DateTime CreatedAt { get; set; }
 }
 
 public class GestureRecognizer
 {
     public async Task<GestureRecognitionResult> RecognizeAsync(HandTrackingData handData)
     {
         await Task.Delay(10); // 模拟识别时间
         
         // 简化的手势识别逻辑
         var gestureType = DetermineGestureType(handData);
         var confidence = CalculateConfidence(handData, gestureType);
         
         return new GestureRecognitionResult
         {
             GestureType = gestureType,
             Confidence = confidence,
             Position = handData.Position,
             Direction = handData.Direction,
             PinchStrength = handData.PinchStrength
         };
     }
     
     private GestureType DetermineGestureType(HandTrackingData handData)
     {
         // 简化的手势类型判断
         if (handData.PinchStrength > 0.8) return GestureType.Pinch;
         if (handData.Velocity.Length() > 2.0f) return GestureType.Swipe;
         return GestureType.Tap;
     }
     
     private double CalculateConfidence(HandTrackingData handData, GestureType gestureType)
     {
         // 简化的置信度计算
         var random = new Random();
         return 0.7 + random.NextDouble() * 0.3; // 70%-100%
     }
 }
 
 public class HandTrackingData
 {
     public Vector3 Position { get; set; }
     public Vector3 Direction { get; set; }
     public Vector3 Velocity { get; set; }
     public float PinchStrength { get; set; }
     public DateTime Timestamp { get; set; }
 }
 
 public class GestureRecognitionResult
 {
     public GestureType GestureType { get; set; }
     public double Confidence { get; set; }
     public Vector3 Position { get; set; }
     public Vector3 Direction { get; set; }
     public float PinchStrength { get; set; }
 }
 
 public enum GestureType
 {
     Tap,
     Pinch,
     Swipe,
     Grab,
     Point
 }
 
 public class VREnvironment
 {
     public Guid Id { get; set; }
     public string Name { get; set; } = string.Empty;
     public DateTime CreatedAt { get; set; }
     public List<VRObject> Objects { get; set; } = new();
     public LightingConfig Lighting { get; set; } = new();
     public PhysicsEngine Physics { get; set; } = new();
 }
 
 public class VREnvironmentConfig
 {
     public string Name { get; set; } = string.Empty;
     public List<string> AssetPaths { get; set; } = new();
     public LightingConfig Lighting { get; set; } = new();
     public Vector3 Gravity { get; set; } = new(0, -9.81f, 0);
     public bool CollisionDetection { get; set; } = true;
 }
 
 public class LightingConfig
 {
     public Vector3 AmbientColor { get; set; } = Vector3.One * 0.2f;
     public Vector3 DirectionalLightColor { get; set; } = Vector3.One;
     public Vector3 DirectionalLightDirection { get; set; } = new(0, -1, 0);
 }
 
 public class PhysicsEngine
 {
     public void Initialize(Vector3 gravity, bool enableCollisionDetection)
     {
         // 初始化物理引擎
     }
 }
 
 public class CollaborativeSession
 {
     public Guid Id { get; set; }
     public string Name { get; set; } = string.Empty;
     public DateTime CreatedAt { get; set; }
     public List<Participant> Participants { get; set; } = new();
     public List<SharedObject> SharedObjects { get; set; } = new();
 }
 
 public class Participant
 {
     public Guid Id { get; set; }
     public Guid UserId { get; set; }
     public string UserName { get; set; } = string.Empty;
     public DateTime JoinedAt { get; set; }
     public Avatar Avatar { get; set; } = new();
     public Vector3 Position { get; set; }
     public Quaternion Rotation { get; set; }
 }
 
 public class SharedObject
 {
     public Guid Id { get; set; }
     public string Name { get; set; } = string.Empty;
     public Vector3 Position { get; set; }
     public Quaternion Rotation { get; set; }
     public Guid OwnerId { get; set; }
     public DateTime LastModified { get; set; }
 }
 
 public class Avatar
 {
     public Guid Id { get; set; }
     public Guid UserId { get; set; }
     public string Name { get; set; } = string.Empty;
     public string ModelPath { get; set; } = string.Empty;
     public Vector3 Position { get; set; }
     public Quaternion Rotation { get; set; }
 }
 
 public class Camera
 {
     public Vector3 Position { get; set; }
     public Vector3 Forward { get; set; }
     public float FarPlane { get; set; } = 1000f;
 }
 
 public class RenderingContext
 {
     public Camera Camera { get; set; } = new();
     public DateTime FrameTime { get; set; }
 }
 
 public class RenderBatch
 {
     public string MaterialId { get; set; } = string.Empty;
     public List<IRenderable> Objects { get; set; } = new();
 }
 
 public class Ray
 {
     public Vector3 Origin { get; set; }
     public Vector3 Direction { get; set; }
     
     public Ray(Vector3 origin, Vector3 direction)
     {
         Origin = origin;
         Direction = direction;
     }
 }

跨平台移动开发

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Text.Json;

// .NET MAUI 跨平台应用框架
public class CrossPlatformMobileApp
{
    private readonly ILogger<CrossPlatformMobileApp> _logger;
    private readonly IPlatformService _platformService;
    private readonly IDataSyncService _dataSyncService;
    private readonly INotificationService _notificationService;
    
    public CrossPlatformMobileApp(
        ILogger<CrossPlatformMobileApp> logger,
        IPlatformService platformService,
        IDataSyncService dataSyncService,
        INotificationService notificationService)
    {
        _logger = logger;
        _platformService = platformService;
        _dataSyncService = dataSyncService;
        _notificationService = notificationService;
    }
    
    // 应用初始化
    public async Task InitializeAsync()
    {
        _logger.LogInformation("Initializing cross-platform mobile app...");
        
        // 检测平台信息
        var platformInfo = await _platformService.GetPlatformInfoAsync();
        _logger.LogInformation("Running on {Platform} {Version}", 
            platformInfo.Platform, platformInfo.Version);
        
        // 初始化数据同步
        await _dataSyncService.InitializeAsync();
        
        // 注册推送通知
        await _notificationService.RegisterForNotificationsAsync();
        
        _logger.LogInformation("App initialization completed");
    }
    
    // 用户认证
    public async Task<AuthenticationResult> AuthenticateUserAsync(string username, string password)
    {
        try
        {
            _logger.LogInformation("Authenticating user: {Username}", username);
            
            var authRequest = new AuthenticationRequest
            {
                Username = username,
                Password = password,
                DeviceId = await _platformService.GetDeviceIdAsync(),
                Platform = await _platformService.GetPlatformInfoAsync()
            };
            
            var result = await AuthenticateWithServerAsync(authRequest);
            
            if (result.IsSuccess)
            {
                // 保存认证令牌
                await _platformService.SecureStorageSetAsync("auth_token", result.Token);
                await _platformService.SecureStorageSetAsync("refresh_token", result.RefreshToken);
                
                _logger.LogInformation("User authenticated successfully");
            }
            else
            {
                _logger.LogWarning("Authentication failed: {Error}", result.ErrorMessage);
            }
            
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Authentication error");
            return new AuthenticationResult
            {
                IsSuccess = false,
                ErrorMessage = "Authentication failed due to network error"
            };
        }
    }
    
    // 数据同步
    public async Task<SyncResult> SyncDataAsync()
    {
        _logger.LogInformation("Starting data synchronization...");
        
        var syncResult = new SyncResult
        {
            StartTime = DateTime.UtcNow,
            SyncedItems = new List<SyncedItem>()
        };
        
        try
        {
            // 检查网络连接
            var isConnected = await _platformService.IsNetworkAvailableAsync();
            if (!isConnected)
            {
                _logger.LogWarning("No network connection available for sync");
                syncResult.Status = SyncStatus.Failed;
                syncResult.ErrorMessage = "No network connection";
                return syncResult;
            }
            
            // 同步用户数据
            var userDataSync = await _dataSyncService.SyncUserDataAsync();
            syncResult.SyncedItems.AddRange(userDataSync);
            
            // 同步应用设置
            var settingsSync = await _dataSyncService.SyncSettingsAsync();
            syncResult.SyncedItems.AddRange(settingsSync);
            
            // 同步离线数据
            var offlineDataSync = await _dataSyncService.SyncOfflineDataAsync();
            syncResult.SyncedItems.AddRange(offlineDataSync);
            
            syncResult.Status = SyncStatus.Success;
            syncResult.EndTime = DateTime.UtcNow;
            
            _logger.LogInformation("Data sync completed. Synced {ItemCount} items", 
                syncResult.SyncedItems.Count);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Data sync failed");
            syncResult.Status = SyncStatus.Failed;
            syncResult.ErrorMessage = ex.Message;
            syncResult.EndTime = DateTime.UtcNow;
        }
        
        return syncResult;
    }
    
    // 推送通知处理
    public async Task HandlePushNotificationAsync(PushNotification notification)
    {
        _logger.LogInformation("Received push notification: {Title}", notification.Title);
        
        try
        {
            // 处理不同类型的通知
            switch (notification.Type)
            {
                case NotificationType.Message:
                    await HandleMessageNotificationAsync(notification);
                    break;
                case NotificationType.Update:
                    await HandleUpdateNotificationAsync(notification);
                    break;
                case NotificationType.Alert:
                    await HandleAlertNotificationAsync(notification);
                    break;
                default:
                    _logger.LogWarning("Unknown notification type: {Type}", notification.Type);
                    break;
            }
            
            // 更新通知徽章
            await _notificationService.UpdateBadgeCountAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error handling push notification");
        }
    }
    
    // 离线数据管理
    public async Task<T?> GetOfflineDataAsync<T>(string key) where T : class
    {
        try
        {
            var data = await _platformService.LocalStorageGetAsync(key);
            if (string.IsNullOrEmpty(data))
            {
                return null;
            }
            
            return JsonSerializer.Deserialize<T>(data);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error retrieving offline data for key: {Key}", key);
            return null;
        }
    }
    
    public async Task SaveOfflineDataAsync<T>(string key, T data) where T : class
    {
        try
        {
            var json = JsonSerializer.Serialize(data);
            await _platformService.LocalStorageSetAsync(key, json);
            
            // 标记为需要同步
            await _dataSyncService.MarkForSyncAsync(key, typeof(T).Name);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error saving offline data for key: {Key}", key);
        }
    }
    
    // 设备功能访问
    public async Task<LocationData?> GetCurrentLocationAsync()
    {
        try
        {
            var hasPermission = await _platformService.RequestLocationPermissionAsync();
            if (!hasPermission)
            {
                _logger.LogWarning("Location permission denied");
                return null;
            }
            
            var location = await _platformService.GetLocationAsync();
            _logger.LogInformation("Current location: {Latitude}, {Longitude}", 
                location.Latitude, location.Longitude);
            
            return location;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting current location");
            return null;
        }
    }
    
    public async Task<CameraResult?> TakePictureAsync()
    {
        try
        {
            var hasPermission = await _platformService.RequestCameraPermissionAsync();
            if (!hasPermission)
            {
                _logger.LogWarning("Camera permission denied");
                return null;
            }
            
            var result = await _platformService.TakePictureAsync();
            
            if (result != null)
            {
                // 保存到本地存储
                var fileName = $"photo_{DateTime.UtcNow:yyyyMMdd_HHmmss}.jpg";
                await _platformService.SaveFileAsync(fileName, result.ImageData);
                
                _logger.LogInformation("Picture taken and saved: {FileName}", fileName);
            }
            
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error taking picture");
            return null;
        }
    }
    
    // 性能监控
    public async Task<PerformanceMetrics> GetPerformanceMetricsAsync()
    {
        var metrics = new PerformanceMetrics
        {
            Timestamp = DateTime.UtcNow,
            MemoryUsage = await _platformService.GetMemoryUsageAsync(),
            CpuUsage = await _platformService.GetCpuUsageAsync(),
            BatteryLevel = await _platformService.GetBatteryLevelAsync(),
            NetworkStatus = await _platformService.GetNetworkStatusAsync(),
            StorageUsage = await _platformService.GetStorageUsageAsync()
        };
        
        _logger.LogDebug("Performance metrics: Memory={MemoryMB}MB, CPU={CpuPercent}%, Battery={BatteryPercent}%",
            metrics.MemoryUsage, metrics.CpuUsage, metrics.BatteryLevel);
        
        return metrics;
    }
    
    // 应用生命周期管理
    public async Task OnAppSuspendingAsync()
    {
        _logger.LogInformation("App suspending - saving state...");
        
        // 保存应用状态
        var appState = new AppState
        {
            LastActiveTime = DateTime.UtcNow,
            CurrentPage = "MainPage", // 示例
            UserData = await GetCurrentUserDataAsync()
        };
        
        await SaveOfflineDataAsync("app_state", appState);
        
        // 停止后台任务
        await _dataSyncService.StopBackgroundSyncAsync();
    }
    
    public async Task OnAppResumingAsync()
    {
        _logger.LogInformation("App resuming - restoring state...");
        
        // 恢复应用状态
        var appState = await GetOfflineDataAsync<AppState>("app_state");
        if (appState != null)
        {
            await RestoreAppStateAsync(appState);
        }
        
        // 重新启动后台任务
        await _dataSyncService.StartBackgroundSyncAsync();
        
        // 检查是否需要同步数据
        var lastSyncTime = await _dataSyncService.GetLastSyncTimeAsync();
        if (DateTime.UtcNow - lastSyncTime > TimeSpan.FromMinutes(30))
        {
            _ = Task.Run(async () => await SyncDataAsync());
        }
    }
    
    private async Task<AuthenticationResult> AuthenticateWithServerAsync(AuthenticationRequest request)
    {
        // 模拟服务器认证
        await Task.Delay(1000);
        
        if (request.Username == "admin" && request.Password == "password")
        {
            return new AuthenticationResult
            {
                IsSuccess = true,
                Token = Guid.NewGuid().ToString(),
                RefreshToken = Guid.NewGuid().ToString(),
                ExpiresAt = DateTime.UtcNow.AddHours(24)
            };
        }
        
        return new AuthenticationResult
        {
            IsSuccess = false,
            ErrorMessage = "Invalid username or password"
        };
    }
    
    private async Task HandleMessageNotificationAsync(PushNotification notification)
    {
        // 处理消息通知
        _logger.LogInformation("Handling message notification");
        await Task.CompletedTask;
    }
    
    private async Task HandleUpdateNotificationAsync(PushNotification notification)
    {
        // 处理更新通知
        _logger.LogInformation("Handling update notification");
        await Task.CompletedTask;
    }
    
    private async Task HandleAlertNotificationAsync(PushNotification notification)
    {
        // 处理警报通知
        _logger.LogInformation("Handling alert notification");
        await Task.CompletedTask;
    }
    
    private async Task<UserData> GetCurrentUserDataAsync()
    {
        // 获取当前用户数据
        return new UserData
        {
            UserId = Guid.NewGuid(),
            Username = "current_user",
            LastLoginTime = DateTime.UtcNow
        };
    }
    
    private async Task RestoreAppStateAsync(AppState appState)
     {
         // 恢复应用状态
         _logger.LogInformation("Restoring app state from {LastActiveTime}", appState.LastActiveTime);
         await Task.CompletedTask;
     }
 }

 // 跨平台服务接口
 public interface IPlatformService
 {
     Task<PlatformInfo> GetPlatformInfoAsync();
     Task<string> GetDeviceIdAsync();
     Task<bool> IsNetworkAvailableAsync();
     Task<bool> RequestLocationPermissionAsync();
     Task<bool> RequestCameraPermissionAsync();
     Task<LocationData> GetLocationAsync();
     Task<CameraResult> TakePictureAsync();
     Task<string> LocalStorageGetAsync(string key);
     Task LocalStorageSetAsync(string key, string value);
     Task<string> SecureStorageGetAsync(string key);
     Task SecureStorageSetAsync(string key, string value);
     Task SaveFileAsync(string fileName, byte[] data);
     Task<double> GetMemoryUsageAsync();
     Task<double> GetCpuUsageAsync();
     Task<double> GetBatteryLevelAsync();
     Task<NetworkStatus> GetNetworkStatusAsync();
     Task<StorageInfo> GetStorageUsageAsync();
 }
 
 public interface IDataSyncService
 {
     Task InitializeAsync();
     Task<List<SyncedItem>> SyncUserDataAsync();
     Task<List<SyncedItem>> SyncSettingsAsync();
     Task<List<SyncedItem>> SyncOfflineDataAsync();
     Task MarkForSyncAsync(string key, string dataType);
     Task StartBackgroundSyncAsync();
     Task StopBackgroundSyncAsync();
     Task<DateTime> GetLastSyncTimeAsync();
 }
 
 public interface INotificationService
 {
     Task RegisterForNotificationsAsync();
     Task UpdateBadgeCountAsync();
 }
 
 // 跨平台数据模型
 public class PlatformInfo
 {
     public string Platform { get; set; } = string.Empty;
     public string Version { get; set; } = string.Empty;
     public string DeviceModel { get; set; } = string.Empty;
     public string OperatingSystem { get; set; } = string.Empty;
 }
 
 public class AuthenticationRequest
 {
     public string Username { get; set; } = string.Empty;
     public string Password { get; set; } = string.Empty;
     public string DeviceId { get; set; } = string.Empty;
     public PlatformInfo Platform { get; set; } = new();
 }
 
 public class AuthenticationResult
 {
     public bool IsSuccess { get; set; }
     public string Token { get; set; } = string.Empty;
     public string RefreshToken { get; set; } = string.Empty;
     public DateTime ExpiresAt { get; set; }
     public string ErrorMessage { get; set; } = string.Empty;
 }
 
 public class SyncResult
 {
     public DateTime StartTime { get; set; }
     public DateTime EndTime { get; set; }
     public SyncStatus Status { get; set; }
     public List<SyncedItem> SyncedItems { get; set; } = new();
     public string ErrorMessage { get; set; } = string.Empty;
 }
 
 public enum SyncStatus
 {
     Success,
     Failed,
     Partial
 }
 
 public class SyncedItem
 {
     public string Key { get; set; } = string.Empty;
     public string DataType { get; set; } = string.Empty;
     public DateTime SyncTime { get; set; }
     public SyncOperation Operation { get; set; }
 }
 
 public enum SyncOperation
 {
     Create,
     Update,
     Delete
 }
 
 public class PushNotification
 {
     public string Title { get; set; } = string.Empty;
     public string Body { get; set; } = string.Empty;
     public NotificationType Type { get; set; }
     public Dictionary<string, string> Data { get; set; } = new();
     public DateTime ReceivedAt { get; set; }
 }
 
 public enum NotificationType
 {
     Message,
     Update,
     Alert
 }
 
 public class LocationData
 {
     public double Latitude { get; set; }
     public double Longitude { get; set; }
     public double Altitude { get; set; }
     public double Accuracy { get; set; }
     public DateTime Timestamp { get; set; }
 }
 
 public class CameraResult
 {
     public byte[] ImageData { get; set; } = Array.Empty<byte>();
     public string FileName { get; set; } = string.Empty;
     public DateTime CapturedAt { get; set; }
     public int Width { get; set; }
     public int Height { get; set; }
 }
 
 public class PerformanceMetrics
 {
     public DateTime Timestamp { get; set; }
     public double MemoryUsage { get; set; }
     public double CpuUsage { get; set; }
     public double BatteryLevel { get; set; }
     public NetworkStatus NetworkStatus { get; set; }
     public StorageInfo StorageUsage { get; set; } = new();
 }
 
 public class NetworkStatus
 {
     public bool IsConnected { get; set; }
     public string ConnectionType { get; set; } = string.Empty;
     public double SignalStrength { get; set; }
 }
 
 public class StorageInfo
 {
     public long TotalSpace { get; set; }
     public long FreeSpace { get; set; }
     public long UsedSpace { get; set; }
 }
 
 public class AppState
 {
     public DateTime LastActiveTime { get; set; }
     public string CurrentPage { get; set; } = string.Empty;
     public UserData UserData { get; set; } = new();
 }
 
 public class UserData
 {
     public Guid UserId { get; set; }
     public string Username { get; set; } = string.Empty;
     public DateTime LastLoginTime { get; set; }
 }

实践练习

练习1:构建云原生微服务系统

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Text.Json;

// 云原生微服务示例
public class CloudNativeMicroservice
{
    private readonly ILogger<CloudNativeMicroservice> _logger;
    private readonly IServiceDiscovery _serviceDiscovery;
    private readonly IConfigurationManager _configManager;
    private readonly IHealthCheckService _healthCheck;
    
    public CloudNativeMicroservice(
        ILogger<CloudNativeMicroservice> logger,
        IServiceDiscovery serviceDiscovery,
        IConfigurationManager configManager,
        IHealthCheckService healthCheck)
    {
        _logger = logger;
        _serviceDiscovery = serviceDiscovery;
        _configManager = configManager;
        _healthCheck = healthCheck;
    }
    
    // 服务启动
    public async Task StartAsync()
    {
        _logger.LogInformation("Starting cloud native microservice...");
        
        // 注册服务
        var serviceInfo = new ServiceInfo
        {
            ServiceId = Guid.NewGuid().ToString(),
            ServiceName = "user-service",
            Version = "1.0.0",
            Host = "localhost",
            Port = 8080,
            HealthCheckUrl = "/health",
            Tags = new[] { "api", "user", "v1" }
        };
        
        await _serviceDiscovery.RegisterServiceAsync(serviceInfo);
        
        // 启动健康检查
        await _healthCheck.StartAsync();
        
        _logger.LogInformation("Microservice started successfully");
    }
    
    // 处理业务请求
    public async Task<ApiResponse<T>> HandleRequestAsync<T>(ApiRequest request)
    {
        var correlationId = Guid.NewGuid().ToString();
        
        using var scope = _logger.BeginScope(new Dictionary<string, object>
        {
            ["CorrelationId"] = correlationId,
            ["RequestId"] = request.RequestId,
            ["UserId"] = request.UserId
        });
        
        try
        {
            _logger.LogInformation("Processing request: {RequestType}", request.RequestType);
            
            // 验证请求
            var validationResult = await ValidateRequestAsync(request);
            if (!validationResult.IsValid)
            {
                return new ApiResponse<T>
                {
                    Success = false,
                    ErrorMessage = validationResult.ErrorMessage,
                    CorrelationId = correlationId
                };
            }
            
            // 处理业务逻辑
            var result = await ProcessBusinessLogicAsync<T>(request);
            
            // 记录审计日志
            await LogAuditEventAsync(request, result, correlationId);
            
            return new ApiResponse<T>
            {
                Success = true,
                Data = result,
                CorrelationId = correlationId
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error processing request");
            
            return new ApiResponse<T>
            {
                Success = false,
                ErrorMessage = "Internal server error",
                CorrelationId = correlationId
            };
        }
    }
    
    // 服务发现和负载均衡
    public async Task<ServiceInstance?> DiscoverServiceAsync(string serviceName)
    {
        var services = await _serviceDiscovery.GetHealthyServicesAsync(serviceName);
        
        if (!services.Any())
        {
            _logger.LogWarning("No healthy instances found for service: {ServiceName}", serviceName);
            return null;
        }
        
        // 简单的轮询负载均衡
        var selectedService = services[new Random().Next(services.Count)];
        
        _logger.LogDebug("Selected service instance: {ServiceId} for {ServiceName}", 
            selectedService.ServiceId, serviceName);
        
        return selectedService;
    }
    
    // 配置热更新
    public async Task HandleConfigurationChangeAsync(string configKey, string newValue)
    {
        _logger.LogInformation("Configuration changed: {Key} = {Value}", configKey, newValue);
        
        try
        {
            await _configManager.UpdateConfigurationAsync(configKey, newValue);
            
            // 通知其他组件配置已更改
            await NotifyConfigurationChangeAsync(configKey, newValue);
            
            _logger.LogInformation("Configuration updated successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to update configuration");
        }
    }
    
    // 分布式追踪
    public async Task<TraceContext> StartTraceAsync(string operationName)
    {
        var traceContext = new TraceContext
        {
            TraceId = Guid.NewGuid().ToString(),
            SpanId = Guid.NewGuid().ToString(),
            OperationName = operationName,
            StartTime = DateTime.UtcNow
        };
        
        _logger.LogInformation("Started trace: {TraceId} for operation: {OperationName}", 
            traceContext.TraceId, operationName);
        
        return traceContext;
    }
    
    public async Task FinishTraceAsync(TraceContext traceContext, bool success = true)
    {
        traceContext.EndTime = DateTime.UtcNow;
        traceContext.Duration = traceContext.EndTime - traceContext.StartTime;
        traceContext.Success = success;
        
        _logger.LogInformation("Finished trace: {TraceId}, Duration: {Duration}ms, Success: {Success}", 
            traceContext.TraceId, traceContext.Duration.TotalMilliseconds, success);
        
        // 发送追踪数据到追踪系统
        await SendTraceDataAsync(traceContext);
    }
    
    private async Task<ValidationResult> ValidateRequestAsync(ApiRequest request)
    {
        // 实现请求验证逻辑
        if (string.IsNullOrEmpty(request.RequestId))
        {
            return new ValidationResult
            {
                IsValid = false,
                ErrorMessage = "Request ID is required"
            };
        }
        
        return new ValidationResult { IsValid = true };
    }
    
    private async Task<T> ProcessBusinessLogicAsync<T>(ApiRequest request)
    {
        // 模拟业务逻辑处理
        await Task.Delay(100);
        
        // 返回模拟结果
        return (T)(object)"Business logic result";
    }
    
    private async Task LogAuditEventAsync<T>(ApiRequest request, T result, string correlationId)
    {
        var auditEvent = new AuditEvent
        {
            EventId = Guid.NewGuid().ToString(),
            CorrelationId = correlationId,
            UserId = request.UserId,
            Action = request.RequestType,
            Timestamp = DateTime.UtcNow,
            Details = JsonSerializer.Serialize(new { Request = request, Result = result })
        };
        
        _logger.LogInformation("Audit event logged: {EventId}", auditEvent.EventId);
        await Task.CompletedTask;
    }
    
    private async Task NotifyConfigurationChangeAsync(string configKey, string newValue)
    {
        // 通知配置变更
        _logger.LogDebug("Notifying configuration change: {Key}", configKey);
        await Task.CompletedTask;
    }
    
    private async Task SendTraceDataAsync(TraceContext traceContext)
    {
        // 发送追踪数据
        _logger.LogDebug("Sending trace data: {TraceId}", traceContext.TraceId);
        await Task.CompletedTask;
    }
}

练习2:构建智能边缘计算平台

using Microsoft.Extensions.Logging;
using System.Text.Json;

// 智能边缘计算平台
public class IntelligentEdgeComputingPlatform
{
    private readonly ILogger<IntelligentEdgeComputingPlatform> _logger;
    private readonly IEdgeDeviceManager _deviceManager;
    private readonly IEdgeAIProcessor _aiProcessor;
    private readonly ICloudConnector _cloudConnector;
    private readonly Dictionary<string, EdgeDevice> _connectedDevices;
    
    public IntelligentEdgeComputingPlatform(
        ILogger<IntelligentEdgeComputingPlatform> logger,
        IEdgeDeviceManager deviceManager,
        IEdgeAIProcessor aiProcessor,
        ICloudConnector cloudConnector)
    {
        _logger = logger;
        _deviceManager = deviceManager;
        _aiProcessor = aiProcessor;
        _cloudConnector = cloudConnector;
        _connectedDevices = new Dictionary<string, EdgeDevice>();
    }
    
    // 设备连接管理
    public async Task<bool> ConnectDeviceAsync(EdgeDevice device)
    {
        try
        {
            _logger.LogInformation("Connecting edge device: {DeviceId}", device.DeviceId);
            
            // 验证设备
            var isValid = await _deviceManager.ValidateDeviceAsync(device);
            if (!isValid)
            {
                _logger.LogWarning("Device validation failed: {DeviceId}", device.DeviceId);
                return false;
            }
            
            // 建立连接
            await _deviceManager.EstablishConnectionAsync(device);
            
            // 注册设备
            _connectedDevices[device.DeviceId] = device;
            device.Status = DeviceStatus.Connected;
            device.LastHeartbeat = DateTime.UtcNow;
            
            // 启动数据收集
            _ = Task.Run(() => StartDataCollectionAsync(device));
            
            _logger.LogInformation("Device connected successfully: {DeviceId}", device.DeviceId);
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to connect device: {DeviceId}", device.DeviceId);
            return false;
        }
    }
    
    // 实时数据处理
    public async Task ProcessSensorDataAsync(string deviceId, SensorData sensorData)
    {
        if (!_connectedDevices.TryGetValue(deviceId, out var device))
        {
            _logger.LogWarning("Received data from unknown device: {DeviceId}", deviceId);
            return;
        }
        
        try
        {
            _logger.LogDebug("Processing sensor data from device: {DeviceId}", deviceId);
            
            // 数据预处理
            var preprocessedData = await PreprocessSensorDataAsync(sensorData);
            
            // AI 推理
            var aiResult = await _aiProcessor.ProcessDataAsync(preprocessedData);
            
            // 实时决策
            var decision = await MakeRealTimeDecisionAsync(device, aiResult);
            
            // 执行决策
            if (decision.RequiresAction)
            {
                await ExecuteDecisionAsync(device, decision);
            }
            
            // 数据聚合和缓存
            await AggregateAndCacheDataAsync(deviceId, sensorData, aiResult);
            
            // 检查是否需要上传到云端
            if (ShouldUploadToCloud(aiResult))
            {
                await _cloudConnector.UploadDataAsync(deviceId, sensorData, aiResult);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error processing sensor data from device: {DeviceId}", deviceId);
        }
    }
    
    // 边缘 AI 模型管理
    public async Task<bool> DeployAIModelAsync(string deviceId, AIModel model)
    {
        if (!_connectedDevices.TryGetValue(deviceId, out var device))
        {
            _logger.LogWarning("Cannot deploy model to unknown device: {DeviceId}", deviceId);
            return false;
        }
        
        try
        {
            _logger.LogInformation("Deploying AI model {ModelId} to device {DeviceId}", 
                model.ModelId, deviceId);
            
            // 检查设备资源
            var resourceCheck = await CheckDeviceResourcesAsync(device, model);
            if (!resourceCheck.HasSufficientResources)
            {
                _logger.LogWarning("Insufficient resources on device {DeviceId} for model {ModelId}", 
                    deviceId, model.ModelId);
                return false;
            }
            
            // 下载模型到设备
            await _deviceManager.DownloadModelAsync(device, model);
            
            // 部署模型
            await _aiProcessor.DeployModelAsync(deviceId, model);
            
            // 验证部署
            var isDeployed = await _aiProcessor.ValidateModelDeploymentAsync(deviceId, model.ModelId);
            
            if (isDeployed)
            {
                device.DeployedModels.Add(model);
                _logger.LogInformation("AI model deployed successfully: {ModelId} on {DeviceId}", 
                    model.ModelId, deviceId);
            }
            
            return isDeployed;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to deploy AI model {ModelId} to device {DeviceId}", 
                model.ModelId, deviceId);
            return false;
        }
    }
    
    // 设备集群协调
    public async Task<ClusterOperationResult> CoordinateClusterOperationAsync(ClusterOperation operation)
    {
        _logger.LogInformation("Coordinating cluster operation: {OperationType}", operation.OperationType);
        
        var result = new ClusterOperationResult
        {
            OperationId = operation.OperationId,
            StartTime = DateTime.UtcNow,
            DeviceResults = new Dictionary<string, DeviceOperationResult>()
        };
        
        try
        {
            // 选择参与设备
            var participatingDevices = SelectDevicesForOperation(operation);
            
            // 并行执行操作
            var tasks = participatingDevices.Select(async device =>
            {
                var deviceResult = await ExecuteDeviceOperationAsync(device, operation);
                result.DeviceResults[device.DeviceId] = deviceResult;
                return deviceResult;
            });
            
            await Task.WhenAll(tasks);
            
            // 聚合结果
            result.Success = result.DeviceResults.Values.All(r => r.Success);
            result.EndTime = DateTime.UtcNow;
            
            _logger.LogInformation("Cluster operation completed: {OperationId}, Success: {Success}", 
                operation.OperationId, result.Success);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Cluster operation failed: {OperationId}", operation.OperationId);
            result.Success = false;
            result.ErrorMessage = ex.Message;
            result.EndTime = DateTime.UtcNow;
        }
        
        return result;
    }
    
    private async Task StartDataCollectionAsync(EdgeDevice device)
    {
        while (device.Status == DeviceStatus.Connected)
        {
            try
            {
                // 收集传感器数据
                var sensorData = await _deviceManager.CollectSensorDataAsync(device);
                
                if (sensorData != null)
                {
                    await ProcessSensorDataAsync(device.DeviceId, sensorData);
                }
                
                // 更新心跳
                device.LastHeartbeat = DateTime.UtcNow;
                
                await Task.Delay(1000); // 1秒间隔
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in data collection for device: {DeviceId}", device.DeviceId);
                await Task.Delay(5000); // 错误时等待5秒
            }
        }
    }
    
    private async Task<SensorData> PreprocessSensorDataAsync(SensorData rawData)
    {
        // 数据清洗和预处理
        var processedData = new SensorData
        {
            DeviceId = rawData.DeviceId,
            Timestamp = rawData.Timestamp,
            SensorType = rawData.SensorType,
            Value = FilterNoiseFromValue(rawData.Value),
            Unit = rawData.Unit
        };
        
        return processedData;
    }
    
    private double FilterNoiseFromValue(double rawValue)
    {
        // 简单的噪声过滤
        return Math.Round(rawValue, 2);
    }
    
    private async Task<EdgeDecision> MakeRealTimeDecisionAsync(EdgeDevice device, AIProcessingResult aiResult)
    {
        var decision = new EdgeDecision
        {
            DecisionId = Guid.NewGuid().ToString(),
            DeviceId = device.DeviceId,
            Timestamp = DateTime.UtcNow,
            RequiresAction = false
        };
        
        // 基于 AI 结果做决策
        if (aiResult.Confidence > 0.8 && aiResult.Prediction == "anomaly")
        {
            decision.RequiresAction = true;
            decision.ActionType = "alert";
            decision.ActionParameters = new Dictionary<string, object>
            {
                ["severity"] = "high",
                ["message"] = "Anomaly detected"
            };
        }
        
        return decision;
    }
    
    private async Task ExecuteDecisionAsync(EdgeDevice device, EdgeDecision decision)
    {
        _logger.LogInformation("Executing decision {DecisionId} for device {DeviceId}", 
            decision.DecisionId, device.DeviceId);
        
        switch (decision.ActionType)
        {
            case "alert":
                await SendAlertAsync(device, decision);
                break;
            case "control":
                await SendControlCommandAsync(device, decision);
                break;
            default:
                _logger.LogWarning("Unknown action type: {ActionType}", decision.ActionType);
                break;
        }
    }
    
    private async Task SendAlertAsync(EdgeDevice device, EdgeDecision decision)
    {
        // 发送警报
        _logger.LogWarning("Alert for device {DeviceId}: {Message}", 
            device.DeviceId, decision.ActionParameters["message"]);
        await Task.CompletedTask;
    }
    
    private async Task SendControlCommandAsync(EdgeDevice device, EdgeDecision decision)
    {
        // 发送控制命令
        _logger.LogInformation("Sending control command to device {DeviceId}", device.DeviceId);
        await _deviceManager.SendControlCommandAsync(device, decision.ActionParameters);
    }
    
    private async Task AggregateAndCacheDataAsync(string deviceId, SensorData sensorData, AIProcessingResult aiResult)
    {
        // 数据聚合和缓存逻辑
        _logger.LogDebug("Aggregating data for device: {DeviceId}", deviceId);
        await Task.CompletedTask;
    }
    
    private bool ShouldUploadToCloud(AIProcessingResult aiResult)
    {
        // 决定是否上传到云端
        return aiResult.Confidence > 0.9 || aiResult.Prediction == "critical";
    }
    
    private async Task<ResourceCheckResult> CheckDeviceResourcesAsync(EdgeDevice device, AIModel model)
    {
        // 检查设备资源
        return new ResourceCheckResult
        {
            HasSufficientResources = true,
            AvailableMemory = 1024,
            RequiredMemory = model.MemoryRequirement
        };
    }
    
    private List<EdgeDevice> SelectDevicesForOperation(ClusterOperation operation)
    {
        // 根据操作类型选择设备
        return _connectedDevices.Values
            .Where(d => d.Status == DeviceStatus.Connected)
            .Where(d => d.Capabilities.Contains(operation.RequiredCapability))
            .ToList();
    }
    
    private async Task<DeviceOperationResult> ExecuteDeviceOperationAsync(EdgeDevice device, ClusterOperation operation)
    {
        try
        {
            _logger.LogDebug("Executing operation {OperationType} on device {DeviceId}", 
                operation.OperationType, device.DeviceId);
            
            // 模拟操作执行
            await Task.Delay(100);
            
            return new DeviceOperationResult
            {
                DeviceId = device.DeviceId,
                Success = true,
                ExecutionTime = TimeSpan.FromMilliseconds(100)
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Operation failed on device {DeviceId}", device.DeviceId);
            
            return new DeviceOperationResult
            {
                DeviceId = device.DeviceId,
                Success = false,
                ErrorMessage = ex.Message
            };
        }
    }
}

本章总结

本章深入探讨了 C# 在未来发展趋势和新兴技术领域的应用,涵盖了以下核心内容:

技术领域覆盖

  1. 云原生开发

    • .NET 云原生应用架构设计
    • 容器化和微服务最佳实践
    • Serverless 计算模式应用
    • 云平台集成和自动化部署
  2. 边缘计算

    • .NET IoT 应用开发框架
    • 边缘设备编程和管理
    • 实时数据处理和 AI 推理
    • 设备集群协调和监控
  3. 现代化技术栈

    • .NET 8+ 新特性和语言改进
    • Blazor 全栈开发解决方案
    • gRPC 和现代 API 设计模式
    • 高性能优化技术和最佳实践
  4. 新兴应用领域

    • 区块链和 Web3 开发
    • 量子计算应用模拟
    • AR/VR 应用开发框架
    • 跨平台移动开发解决方案

核心技术能力

  • 架构设计:微服务架构、事件驱动架构、CQRS 模式
  • 性能优化:内存管理、并发处理、缓存策略
  • 安全实践:身份认证、数据加密、安全通信
  • 监控运维:健康检查、日志记录、性能监控
  • 数据处理:实时流处理、批量处理、数据同步

实际应用场景

  • 企业数字化转型:云原生架构迁移和现代化改造
  • 物联网解决方案:智能设备管理和边缘计算平台
  • 人工智能应用:机器学习模型部署和推理服务
  • 移动应用开发:跨平台解决方案和原生性能优化
  • 新兴技术探索:区块链、量子计算、AR/VR 应用

发展趋势展望

随着技术的不断演进,C# 将在以下方面继续发展:

  • 云原生生态:更深度的云平台集成和 Serverless 支持
  • AI/ML 集成:原生机器学习框架和推理引擎
  • 跨平台能力:更好的移动和 Web 开发体验
  • 性能提升:编译时优化和运行时性能改进
  • 开发体验:更智能的工具链和开发环境

通过掌握这些前沿技术和最佳实践,开发者可以构建面向未来的高质量应用程序,在快速变化的技术环境中保持竞争优势。

下一章我们将进行 C# 教程的总结回顾,梳理整个学习路径的核心知识点,并提供进一步学习的建议和资源。 “`