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;
}
相关推荐
游乐码4 小时前
c#泛型约束
开发语言·c#
hoiii1874 小时前
C# 基于 LumiSoft 实现 SIP 客户端方案
前端·c#
yongui478346 小时前
C# 与三菱PLC通讯解决方案
开发语言·c#
jerryinwuhan8 小时前
RDD第二次练习
开发语言·c#
aini_lovee11 小时前
C# 快速搜索磁盘文件解决方案
开发语言·c#
派葛穆13 小时前
汇川PLC-Unity3d与汇川easy521plc进行Modbustcp通讯
unity·c#
游乐码14 小时前
C#List
开发语言·c#·list
Paine Zeng16 小时前
C# + SolidWorks 二次开发 -监听退出草图事件并自动执行逻辑
c#·solidworks二次开发·solidworks api
游乐码16 小时前
C#Dicitionary
算法·c#
SunnyDays101116 小时前
C# 实战:如何高效地将 HTML 转换为可编辑 Word 文档
c#·html转word