[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;
}