2014-09-06 104 views
0

我嘗試使用枚舉與字符串值爲我使用屬性,但它顯示錯誤爲 擴展方法必須在非泛型靜態類中定義擴展方法必須在C#中的非泛型靜態類中定義

public enum CommonMessagesEnum : int 
{ 
    [StringValue("This Operation is not allowed.")] 
    NotAllowed = 1 
} 

public class StringValueAttribute : Attribute 
{   

    public string StringValue { get; protected set; }  


    public StringValueAttribute(string value) 
    { 
     this.StringValue = value; 
    }   

    public static string GetStringValue(this Enum value) 
    { 
     Type type = value.GetType(); 
     FieldInfo fieldInfo = type.GetField(value.ToString());    
     StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];   
     return attribs.Length > 0 ? attribs[0].StringValue : null; 
    } 

} 
+1

那麼,有什麼問題。你爲什麼不將擴展方法移動到另一個類? – Patrick 2014-09-06 06:00:11

回答

2

你有你的方式移動到一個靜態類

public static class ExtensionMethods 
    { 
     public static string GetStringValue(this Enum value) 
     { 
      Type type = value.GetType(); 
      FieldInfo fieldInfo = type.GetField(value.ToString()); 
      StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[]; 
      return attribs.Length > 0 ? attribs[0].StringValue : null; 
     } 
    } 
相關問題