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;
}
相关推荐
bugcome_com3 小时前
C# 程序结构详解:从 Hello World 开始
c#
唐梓航-求职中4 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
bugcome_com7 小时前
阿里云 OSS C# SDK 使用实践与参数详解
阿里云·c#
懒人咖17 小时前
缺料分析时携带用料清单的二开字段
c#·金蝶云星空
bugcome_com17 小时前
深入了解 C# 编程环境及其开发工具
c#
wfserial19 小时前
c#使用微软自带speech选择男声仍然是女声的一种原因
microsoft·c#·speech
阔皮大师21 小时前
INote轻量文本编辑器
java·javascript·python·c#
kylezhao201921 小时前
C# 中的 SOLID 五大设计原则
开发语言·c#
啦啦啦_99991 天前
Redis-5-doFormatAsync()方法
数据库·redis·c#
Porco.w1 天前
C#与三菱PLC FX5U通信
网络·c#