c# - How to convert a type to enum -
i'm trying enum type , i'll explain, have enums (i used string enumerations) explained here.
public enum enum1 { [stringvalue("codeip597")] code = 1, [stringvalue("infoyes")] info = 3 } public enum enum2 { [stringvalue("codenoip")] code = 1, [stringvalue("info95p")] info = 3 } the method "general" this:
private static void general(type enumtype) { var enu = enumtype.toenum(); //i want console.writeline(stringenum.getstringvalue(enu.code)); } i have lot of equals enums each of these contains attribute "code" , "info", want every enumtype put parameter, in variable console return me string value.
for example : if call method
general(typeof(enum1)); the console : codeip597
if call method
general(typeof(enum2)); the console : codenoip
how do? in advance
assuming attribute looks this:
public class stringvalue : attribute { public string name { get; private set; } public stringvalue(string name) { this.name = name; } } then you'll have use reflection pull out attribute , value since there no relation between enums besides value names:
private static void general(type enumtype) { if (!enumtype.isenum) throw new argumentexception("not enum type"); var values = enumtype.getfields(); var code = values.first(f => f.name == "code"); var info = values.first(f => f.name == "info"); string codestring = code.getcustomattributes(false).oftype<stringvalue>().first().name; string infostring = info.getcustomattributes(false).oftype<stringvalue>().first().name; console.writeline(codestring); console.writeline(infostring); } it's not same have in terms of output, demonstrates how string values. may need add additional checks they're types expect or have attributes expect.
Comments
Post a Comment