c# - Dictionary of Enum Values as strings -


i trying make api, 1 function in api takes enum parameter corresponds string used.

public enum packageunitofmeasurement {         lbs,         kgs, }; 

the trivial method code have list every case in code. 30 cases trying avoid , use dictionary data structure, can't seem connect dots on how relate value enum.

if(unit == packageunitofmeasurement.lbs)        uom.code = "02";  //please note value has string else if (unit == packageunitofmeasurement.kgs)        uom.code = "03"; 

here 1 way store mapping in dictionary , retrieve values later:

var mydict = new dictionary<packageunitofmeasurement,string>(); mydict.add(packageunitofmeasurement.lbs, "02"); ...  string code = mydict[packageunitofmeasurement.lbs]; 

another option use decriptionattribute decorate each enumeration item , use reflection read these out, described in 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; 

the benefit of second approach keep mapping close enum , if either changes, don't need hunt other place need update.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -