c# - Generic string to enum conversion -
suppose enum:
public enum syslogsapptypes { none, monitorservice, monitortool };
and here function convert tostring()
representation enum
:
private syslogsapptypes str2syslogsapptypes(string str) { try { syslogsapptypes res = (syslogsapptypes)enum .parse(typeof(syslogsapptypes), str); if (!enum.isdefined(typeof(syslogsapptypes), res)) return syslogsapptypes.none; return res; } catch { return syslogsapptypes.none; } }
is there way make generic ??
i tried:
private t str2enum<t>(string str) { try { t res = (t)enum.parse(typeof(t), str); if (!enum.isdefined(typeof(t), res)) return t.none; return res; } catch { return t.none; } }
but get: 't' 'type parameter', not valid in given context
there t.none
any ?
i think default
keyword need:
private t str2enum<t>(string str) t : struct { try { t res = (t)enum.parse(typeof(t), str); if (!enum.isdefined(typeof(t), res)) return default(t); return res; } catch { return default(t); } }
Comments
Post a Comment