c# - 枚举值字典作为字符串

标签 c# .net string dictionary enums

我正在尝试制作一个 API,该 API 中的一个函数将 Enum 作为参数,然后对应于一个使用的字符串。

public enum PackageUnitOfMeasurement
{
        LBS,
        KGS,
};

编写此代码的简单方法必须列出代码中的每个案例。但由于它们有 30 个案例,所以我试图避免这种情况并使用 Dictionary Data Structure,但我似乎无法将如何将值与枚举相关联。

if(unit == PackageUnitOfMeasurement.LBS)
       uom.Code = "02";  //Please note this value has to be string
else if (unit == PackageUnitOfMeasurement.KGS)
       uom.Code = "03";

最佳答案

这是一种将映射存储在字典中并稍后检索值的方法:

var myDict = new Dictionary<PackageUnitOfMeasurement,string>();
myDict.Add(PackageUnitOfMeasurement.LBS, "02");
...

string code = myDict[PackageUnitOfMeasurement.LBS];

另一种选择是使用类似 DecriptionAttribute 的东西装饰每个枚举项并使用反射来读取它们,如 Getting attributes of Enum's value 中所述:

public enum PackageUnitOfMeasurement
{
        [Description("02")]
        LBS,
        [Description("03")]
        KGS,
};


var type = typeof(PackageUnitOfMeasurement);
var memInfo = type.GetMember(PackageUnitOfMeasurement.LBS.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),
    false);
var description = ((DescriptionAttribute)attributes[0]).Description;

第二种方法的好处是您可以将映射保持在枚举附近,并且如果其中任何一个发生变化,您无需寻找任何其他需要更新的地方。

关于c# - 枚举值字典作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9618670/

相关文章:

c# - 需要帮助使 crc 计算的类线程安全

c++ - 为什么 C++ 标准中没有 std::basic_string 类的构造函数,其参数为 std::string_view 类型

c++ - 将 std::string 和字符数组分成两半(有效地)

c++ - 如何仅使用 boost 将字符串编码为 base64?

c# - 需要覆盖导航方法

c# - 为什么我预期的空对象不为空?

c# - 在 .net Windows 服务中处理停止

c# - 如果不直接在窗口中居中,图像就会消失 [Margin not "0"]

c# - 在 MVC 3 中实现 Controller 创建策略的最佳方式

c# - ASP.Net MVC : Submit array/collection in a single parameter