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;
}
相关推荐
Jeff-Tsai6 小时前
一个不用注册方法的 JSON-RPC 包,怎么决定哪些方法能被调用?
c#·.net·asp.net core·json-rpc
rockey6271 天前
AScript正式推出Template模板引擎
c#
沐言Agent1 天前
做工业上位机,这个 C# 开源框架把 PLC 通讯、流程控制和 MES 对接都备好了
c#·工业上位机
投研帮1 天前
C#文档管理系统开发实战:技术选型、全文检索与并发控制
c#·.net·文档管理系统
2395730492 天前
在 Avalonia 12 上用纯 .NET 重写 Monaco 编辑器:TKCode.Arc CodeEditor / DiffEditor / LSP 深度架构与实战
c#·.net·lsp·avalonia·monaco·codeeditor·tkcode.arc
新*2 天前
在 .NET 里嵌入 IronPython:内存只涨不降的真相与正确的封装姿势
c#·.net·内存优化·ironpython·dlr
2501_930707782 天前
使用C#从 PowerPoint 演示文稿中提取图片
开发语言·c#·powerpoint
zhanghaha13142 天前
C# 系列教程_15 类 Class 保姆级系统教程(面向新手,大量示例 + 底层机理)
java·开发语言·c#
Risehuxyc3 天前
HttpClient怎么传POST参数
c#
zdr尽职尽责7 天前
UnityCli 兼容2022版本
ui·unity·ai·c#·游戏引擎