c# - Search within Enum attribute -


this question has answer here:

i want check in enum passed code exists in of enum or not. problem enum defined below using code attribute.

public enum testenum     {          none,          [code("fmng")]         functionsmanagement,          [code("inst_mast_mgt")]         masterinstmanagement }  [attributeusage(attributetargets.field, allowmultiple = false)]     public class codeattribute : attribute     {         readonly string _code;         public string code         {                         {                 return _code;             }         }         public codeattribute(string code)         {             _code = code;         }     } 

now, have string available (e.g. "fmng") , want search enum enum exists passed string in enum attribute.

how can check/get enum using or passing string? tried using enum.isdefined(typeof(activityenum), "fmng") not working attributes of enum.

here generic function:

    public static object toenum(string codetofind, type t)     {         foreach (var enumvalue in enum.getvalues(t))         {             codeattribute[] codes = (codeattribute[])(enumvalue.gettype().getfield(enumvalue.tostring()).             getcustomattributes(typeof(codeattribute), false));              if (codes.length > 0 && codes[0].code.equals(codetofind, stringcomparison.invariantcultureignorecase) ||                 enumvalue.tostring().equals(codetofind, stringcomparison.invariantcultureignorecase))                 return enumvalue;         }          return null;     } 

usage: var test = toenum("inst_mast_mgt", typeof(testenum));

the above function return enum value if finds defined code attribute or codetofind parameter equal enum's value tostring, can adapt needs.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -