gpt4 book ai didi

c# - 如何从其描述中获取枚举值?

转载 作者:太空狗 更新时间:2023-10-30 00:36:43 26 4
gpt4 key购买 nike

我有一个代表系统中所有 Material 装配代码的枚举:

public enum EAssemblyUnit
{
[Description("UCAL1")]
eUCAL1,
[Description("UCAL1-3CP")]
eUCAL13CP,
[Description("UCAL40-3CP")]
eUCAL403CP, // ...
}

在系统另一部分的遗留代码中,我有标有与枚举描述匹配的字符串的对象。给定其中一个字符串,获取枚举值的最简洁方法是什么?我设想的是这样的:

public EAssemblyUnit FromDescription(string AU)
{
EAssemblyUnit eAU = <value we find with description matching AU>
return eAU;
}

最佳答案

您需要遍历枚举的所有静态字段(这就是它们在反射中的存储方式)找到每个字段的 Description 属性...当您找到正确的字段时,获取该字段的值.

例如:

public static T GetValue<T>(string description)
{
foreach (var field in typeof(T).GetFields())
{
var descriptions = (DescriptionAttribute[])
field.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (descriptions.Any(x => x.Description == description))
{
return (T) field.GetValue(null);
}
}
throw new SomeException("Description not found");
}

(这是通用的,只是为了使其可重复用于不同的枚举。)

很明显,即使您稍微频繁地这样做,您也希望缓存描述,例如:

public static class DescriptionDictionary<T> where T : struct
{
private static readonly Dictionary<string, T> Map =
new Dictionary<string, T>();

static DescriptionDictionary()
{
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException("Must only use with enums");
}
// Could do this with a LINQ query, admittedly...
foreach (var field in typeof(T).GetFields
(BindingFlags.Public | BindingFlags.Static))
{
T value = (T) field.GetValue(null);
foreach (var description in (DescriptionAttribute[])
field.GetCustomAttributes(typeof(DescriptionAttribute), false))
{
// TODO: Decide what to do if a description comes up
// more than once
Map[description.Description] = value;
}
}
}

public static T GetValue(string description)
{
T ret;
if (Map.TryGetValue(description, out ret))
{
return ret;
}
throw new WhateverException("Description not found");
}
}

关于c# - 如何从其描述中获取枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1033260/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com