枚举值字典作为字符串

PUG*_*PUG 3 .net c# string enums dictionary

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

public enum PackageUnitOfMeasurement
{
        LBS,
        KGS,
};
Run Code Online (Sandbox Code Playgroud)

对此进行编码的简单方法必须列出代码中的每个案例.但是因为他们是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";
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 9

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

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

string code = myDict[PackageUnitOfMeasurement.LBS];
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用诸如DecriptionAttribute装饰每个枚举项之类的东西并使用反射来读取它们,如获取Enum值的属性中所述:

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;
Run Code Online (Sandbox Code Playgroud)

第二种方法的好处是您可以使映射保持接近枚举,如果有任何更改,则无需寻找需要更新的任何其他位置.