c# - How to get the data value of an enum in a generic method? -


Thanks to the question, I have succeeded in how to disrupt my generic method to accept enums only.

Now I am trying to create a generic method so that I can tie a drop down to any anonym, by displaying details in the drop-down, value equal to numerical value Enum value.

  Public static object EnumToDataSource & lt; T & gt; () Where T: struct, IConvertible {if type! (Typh (T.IsEnum) / / just throw a new exception (String.Format ("type {0} is not an enumeration.", Typef (t)); VAR q = Enum.GetValues ​​(typeof (T)). Cast & lt; T & gt; (). Selecting (x = & gt; new {ID = DataUtil.ToByte (x), Description = x.ToString ()}) / ToByte () is my own way to safely convert a value without throwing an exception. Orderbie (x => x.Description); Return q; }  

looks good, but ToByte () always returns 0, even though my calculations are clearly set values, such as:

  Public enum TStatus: Outside the byte generic method, if I enter a type of value from  TStatus  to  byte , then {active = 1, idle = 0,} < / Code> 

, it works perfectly inside the normal method, if I try to type T to byte I am a compound Error gets the error. I can not find anything in an anum stable interface to do this.

So, how do I get numeric values ​​of enum inside normal? (I would also accept any other advice about optimizing my code ...)

Edit: Um, er ... have come to know that this Was not working. .. Because there was a bug in my ToByte () method ... (red). Oh ok, thanks anyway - I learned a lot from it!

You can do this (change dataUtil.toByte (x) to x.ToByte (null)) :

  Public static object EnumToDataSource & lt; T & gt; () Where T: struct, IConvertible {if type! (.tif) (t.IsEnum) throw a new exception (string format ("type {0} is not an enumeration.", Typef (t)); Var q = Enum.GetValues ​​(typef (t)) Cast & lt; T & gt; (). Select (x = & gt; new {id = x.ToByte (null), description = x.ToString ()}). Serial (x = & gt; x.Description) .Oir (); Return q; }  

Comments

Popular posts from this blog

c# - ListView onScroll event -

PHP - get image from byte array -

Linux Terminal Problem with Non-Canonical Terminal I/O app -