Generisches Enum.Parse

Da es in C#2 leider noch keine generische Parse-Methode für Enumerations gibt, muss man sich diese selbst schreiben.

C#:
  1.  
  2. public abstract class Enum<T> {
  3.         public static T Parse(string enumElementToParse) {
  4.                 if (Enum.IsDefined(typeof (T), enumElementToParse)) {
  5.                         return (T) Enum.Parse(typeof (T), enumElementToParse, true);
  6.                 }
  7.                 throw new ArgumentException("Enumeration element is not defined in: "+ typeof(T).FullName, enumElementToParse);
  8.         }
  9. }
  10.  

oder als typisierte statische Methode:

C#:
  1.  
  2. public static Parse<T>(string enumElementToParse) {
  3.         if (Enum.IsDefined(typeof (T), enumElementToParse)) {
  4.                 return (T) Enum.Parse(typeof (T), enumElementToParse, true);
  5.         }
  6.         throw new ArgumentException("Enumeration element is not defined in: "+ typeof(T).FullName, enumElementToParse);
  7. }
  8.  

No Responses to “Generisches Enum.Parse”  

  1. No Comments

Leave a Reply