前言

C# 获取枚举描述的方法有很多, 常用的有通过 DescriptionAttribute 反射获取, 进阶的可以加上缓存机制, 减少反射的开销。今天我们还提供一种更加高效的方法,通过增量源生成器生成获取枚举描述的代码。这是在编译层面实现的, 无需反射, 性能更高。

本文的演示代码基于 VS2022 + .NET 8.0 + .NET Standard 2.0

1. 基本反射

这种方法是最常用的方法, 但是反射开销比较大。

public enum Color
{
[Description("红色")]
Red,
[Description("绿色")]
Green,
[Description("蓝色")]
Blue
} public static string GetDescription(Color color)
{
var fieldInfo = typeof(Color).GetField(color.ToString());
var descriptionAttribute = fieldInfo.GetCustomAttribute<DescriptionAttribute>();
return descriptionAttribute?.Description;
}

2. 反射 + 缓存

缓存机制可以减少反射的开销, 避免反射过于频繁。

private static readonly Dictionary<Color, string> _descriptionCache = new Dictionary<Color, string>();

public static string GetDescription(Color color)
{
if (_descriptionCache.TryGetValue(color, out var description))
{
return description;
} var fieldInfo = typeof(Color).GetField(color.ToString());
var descriptionAttribute = fieldInfo.GetCustomAttribute<DescriptionAttribute>();
description = descriptionAttribute?.Description;
_descriptionCache.Add(color, description);
return description;
}

3. 反射 + 缓存 + 泛型类 (推荐)

泛型可以减少代码重复。下面的代码为基本实现, 没有考虑线程安全问题。线程安全问题可以通过锁机制解决。可以使用静态构造函数初始化缓存。或者使用 ConcurrentDictionary 代替 Dictionary。或者使用 Lazy 代替缓存。

public class EnumDescription<T> where T : Enum
{
private static readonly Dictionary<T, string> _descriptionCache = new Dictionary<T, string>(); public static string GetDescription(T value)
{
if (_descriptionCache.TryGetValue(value, out var description))
{
return description;
} var fieldInfo = typeof(T).GetField(value.ToString());
var descriptionAttribute = fieldInfo.GetCustomAttribute<DescriptionAttribute>();
description = descriptionAttribute?.Description;
_descriptionCache.Add(value, description);
return description;
}
}

4. 增量源生成器 (消除反射)

创建增量源生成器类库项目 (.NET Standard 2.0)

  1. 创建一个基于 .NET Standard 2.0 的类库项目名为: SourceGenerator

  2. 添加 NuGet 包 Microsoft.CodeAnalysis.CSharp 版本 4.8.0

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
</PropertyGroup> <ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.8.0" />
</ItemGroup>
</Project>
  1. 添加 EnumDescriptionGenerator 类, 实现 IIncrementalGenerator 接口
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text; [Generator]
public class EnumDescriptionGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var enumDeclarations = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: (syntaxNode, _) => syntaxNode is EnumDeclarationSyntax,
transform: (generatorSyntaxContext, _) =>
{
var enumDeclaration = (EnumDeclarationSyntax)generatorSyntaxContext.Node;
var enumSymbol = generatorSyntaxContext.SemanticModel.GetDeclaredSymbol(enumDeclaration) as INamedTypeSymbol;
return new { EnumDeclaration = enumDeclaration, EnumSymbol = enumSymbol };
})
.Where(t => t.EnumSymbol != null)
.Collect(); var compilationAndEnums = context.CompilationProvider.Combine(enumDeclarations); context.RegisterSourceOutput(compilationAndEnums, (sourceProductionContext, tuple) =>
{
var compilation = tuple.Left;
var enums = tuple.Right; foreach (var item in enums)
{
var enumDeclaration = item.EnumDeclaration;
var enumSymbol = item.EnumSymbol; if (!enumSymbol.GetMembers("GetDescription").Any())
{
var source = GenerateSourceCode(enumSymbol);
sourceProductionContext.AddSource($"{enumSymbol.Name}Descriptions.g.cs", SourceText.From(source, Encoding.UTF8));
}
} });
} // 生成枚举描述扩展方法的代码
private static string GenerateSourceCode(INamedTypeSymbol enumSymbol)
{
var enumName = enumSymbol.Name;
var namespaceName = enumSymbol.ContainingNamespace?.ToString() ?? "Global"; var sb = new StringBuilder();
sb.AppendLine($"namespace {namespaceName};");
sb.AppendLine($"public static partial class {enumName}Extensions");
sb.AppendLine("{");
sb.AppendLine($" public static string GetDescription(this {enumName} value) =>");
sb.AppendLine(" value switch");
sb.AppendLine(" {"); // 4. 遍历枚举成员
foreach (var member in enumSymbol.GetMembers().Where(m => m.Kind == SymbolKind.Field))
{
var description = member.GetAttributes()
.FirstOrDefault(a => a.AttributeClass?.Name == "DescriptionAttribute")
?.ConstructorArguments.FirstOrDefault().Value?.ToString()
?? member.Name; sb.AppendLine($" {enumName}.{member.Name} => \"{description}\",");
} sb.AppendLine(" _ => string.Empty");
sb.AppendLine(" };");
sb.AppendLine("}");
return sb.ToString();
}
}

创建控制台主项目 MainProject

  1. 使用 .NET 8.0 , 引用 SourceGenerator 项目, 注意引用方式如下:
<Project Sdk="Microsoft.NET.Sdk">

	<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup> <ItemGroup>
<ProjectReference Include="..\SourceGenerator\SourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup> </Project>
  1. MainProject 中使用生成的枚举描述扩展方法
namespace MainProject;

class Program
{
static void Main()
{
foreach (var color in Enum.GetValues<Color>())
{
Console.WriteLine(color.GetDescription());
}
Console.ReadKey();
}
}
  1. 编译运行, 编译器会自动生成枚举描述扩展方法的代码。

演示程序截图:

总结

通过增量源生成器, 我们可以在编译期自动生成获取枚举描述的代码, 无需反射, 性能更高。

C# - 获取枚举描述 - 使用增量源生成器的更多相关文章

  1. C#获取枚举描述代码

    public class MusterEnum { /// 获取枚举的描述信息 /// </summary> /// <param name="e">传入枚 ...

  2. .NET--------枚举扩展方法(枚举转list,获取枚举描述)

    /// <summary> /// get enum description by name /// </summary> /// <typeparam name=&qu ...

  3. .NET获取枚举DescriptionAttribute描述信息性能改进的多种方法

    一. DescriptionAttribute的普通使用方式 1.1 使用示例 DescriptionAttribute特性可以用到很多地方,比较常见的就是枚举,通过获取枚举上定义的描述信息在UI上显 ...

  4. C#枚举扩展方法,获取枚举值的描述值以及获取一个枚举类下面所有的元素

    /// <summary> /// 枚举扩展方法 /// </summary> public static class EnumExtension { private stat ...

  5. C#通过反射进行枚举描述相关操作

    C#可以通过反射,来获取枚举的描述信息或通过描述信息获取到指定类型的枚举 /// <summary> /// 获取枚举描述 /// </summary> /// <par ...

  6. 【转载】[C#]枚举操作(从枚举中获取Description,根据Description获取枚举,将枚举转换为ArrayList)工具类

    关键代码: using System; using System.Collections; using System.Collections.Generic; using System.Compone ...

  7. C# 读取枚举描述信息实例

    using System;using System.Collections;using System.Collections.Generic;using System.Linq;using Syste ...

  8. c#枚举 获取枚举键值对、描述等

    using System; using System.Collections.Generic; using System.Collections.Specialized; using System.C ...

  9. .net工具类 获取枚举类型的描述

    一般情况我们会用枚举类型来存储一些状态信息,而这些信息有时候需要在前端展示,所以需要展示中文注释描述. 为了方便获取这些信息,就封装了一个枚举扩展类. /// <summary> /// ...

  10. 枚举Enum转换为List,获取枚举的描述

    代码: public class EnumberHelper { public static List<EnumberEntity> EnumToList<T>() { Lis ...

随机推荐

  1. IM通讯协议专题学习(七):手把手教你如何在NodeJS中从零使用Protobuf

    1.前言 Protobuf是Google开源的一种混合语言数据标准,已被各种互联网项目大量使用. Protobuf最大的特点是数据格式拥有极高的压缩比,这在移动互联时代是极具价值的(因为移动网络流量到 ...

  2. spark (一) 入门 & 安装

    目录 基本概念 spark 核心模块 spark core (核心) spark sql (结构化数据操作) spark streaming (流式数据操作) 部署模式 local(本地模式) sta ...

  3. TagHelper中获取当前Url

    在自定义TagHelper时,我们无法通过TagHelperContext 和 TagHelperOutput 获取到当前路由的信息,我们需要添加注入ViewContext [HtmlAttribut ...

  4. MTK8766 LK GPIO初始化状态设置分析

    问题来源是M.2 Dongle的LED灯在kernel起来之前就亮了,kernel起来之后又初始化成熄灭状态.通过排查硬件规格书.GPIO表格,大概判定是前期软件初始化不正确造成的.通过观察串口打印的 ...

  5. Final Review - 返回天空的雨滴

    目录 Motivations Tricks Conclusions Algorithms And - \[\text{Each moment, now night.} \newcommand{\vct ...

  6. Python串口实现dk-51e1单相交直流标准源通信

    Python实现dk-51e1单相交直流标准源RS232通信 使用RS232,信号源DK51e1的协议帧格式如下: 注意点 配置串口波特率为115200 Check异或和不需要加上第一个0x81的字段 ...

  7. w3cschool-Linux 教程

    https://www.w3cschool.cn/linux/ Linux 安装 本章节我们将为大家介绍 Linux 的安装,安装步骤比较繁琐,现在其实云服务器挺普遍的,价格也便宜,如果自己不想搭建, ...

  8. G1原理—8.如何优化G1中的YGC

    大纲 1.5千QPS的数据报表系统发生性能抖动的优化(停顿时间太小导致新生代上不去) 2.由于产生大量大对象导致系统吞吐量降低的优化(大对象太多频繁Mixed GC) 3.YGC其他相关参数优化之TL ...

  9. idea操作小技巧总结

    一.热键 光标导航前进|后退 Ctrl+Alt+左右方向键 光标转到语句块的头尾 Ctrl+[|] 再次提示函数参数列表 Ctrl+P 插入实时模板 Ctrl+J 文件结构查看 Ctrl+F12 书签 ...

  10. TCP/IP协议栈封装解封装过程

    发送方将用户数据提交给应用程序把数据送达目的地,整个数据封装流程如下: 用户数据首先传送至应用层,添加应用层信息: 完成应用层处理后,数据将往下层传输层继续传送,添加传输层信息(如TCP或UDP,应用 ...