c# 4.0 - Constraining a generic method using Enum methods to T -


i've been trying write utility extension method flagged enum values. purpose method retrieve list of flags enabled.

what wanted this:

 public static ienumerable<t> getflags<t>(this t value) t:enum    {      return enum.getvalues(typeof(t)).oftype<enum>().where(value.hasflag).cast<t>();    } 

however, since generics doesn't work enum type had resort following:

public static ienumerable<t> getflags<t>(this enum value)    {      return enum.getvalues(typeof(t)).oftype<enum>().where(value.hasflag).cast<t>();    } 

is there way around or should resign myself explicitly having declare type every time method called ?

the best can where t : struct.

for non-extension methods, can use ugly trick:

public abstract class enums<temp> temp : class {     public static tenum parse<tenum>(string name) tenum : struct, temp {         return (tenum)enum.parse(typeof(tenum), name);      } } public abstract class enums : enums<enum> { }  enums.parse<datetimekind>("local") 

if want to, can give enums<temp> private constructor , public nested abstract inherited class temp enum, prevent inherited versions non-enums.

you can't use trick make extension methods because extension methods must defined in static class , cannot inherit different class.


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -