c# 属性操作(2)

复制代码
[AttributeUsage(AttributeTargets.Method)]
public sealed class AsyncToSyncWarningAttribute : Attribute
{
}
1. 特性作为标记
  • 特性(Attribute)本质上是附加到代码元素上的"标签"或"注释"。例如,你定义了一个 [AsyncToSyncWarning] 特性,并将其应用于某些方法。
  • 这些特性本身不执行任何逻辑,它们只是提供额外的信息。
2. 手动标注
  • 开发者需要手动 为那些可能存在潜在问题的方法添加这些特性。比如,在你的例子中,你需要明确地为某个异步方法加上 [AsyncToSyncWarning] 标签。
  • 这种方式依赖于开发者的自觉性和对代码的理解。如果开发者忘记添加或者错误地标记了方法,那么这些特性就无法发挥应有的作用。
3. 警告机制的实现
复制代码
public string GetData()
{
    var methodInfo = typeof(DataService).GetMethod(nameof(FetchDataAsync));
    var attribute = methodInfo.GetCustomAttribute<AsyncToSyncWarningAttribute>();

    if (attribute != null)
    {
        Console.WriteLine($"⚠️ {attribute.WarningMessage}");
        Console.WriteLine($"💡 {attribute.Suggestion}");
    }

    return FetchDataAsync().Result;
}
相关推荐
吃一碗粉只付一碗钱14 小时前
10-令牌里的用户主键不要明文
服务器·数据库·sql·sqlserver·c#
胖纸不争17 小时前
EnergyStarZ:让 Windows 后台进程给前台让路的能效管理器(v1.2 发布)
windows·性能优化·c#·win32·ef core
曹牧18 小时前
C#:The operation has timed out
开发语言·c#
He BianGu18 小时前
【WPF-Control教程】IOC 依赖注入
c#·wpf·wpf-control
He BianGu18 小时前
【WPF-Control教程】H.Extensions.Behvaiors 开发文档
c#·wpf·wpf-control
He BianGu19 小时前
【WPF-Control教程】H.Style 开发文档
c#·wpf·wpf-control
He BianGu19 小时前
【WPF-Control教程】MVVM 二次开发文档
c#·wpf·wpf-control
He BianGu19 小时前
【WPF-Control教程】Theme 主题系统二次开发文档
c#·wpf·wpf-control
iCxhust20 小时前
C#双时区时钟设计
开发语言·c#
CSharp精选营20 小时前
.NET 接口从 800ms 干到 60ms:生产环境这几个优化点最关键
性能优化·c#·.net·efcore