必须在c#中的非泛型静态类中定义扩展方法

时间:2014-09-06 05:56:24

标签: c# wpf c#-4.0 enums c#-3.0

我尝试使用带有字符串值的枚举,因为我使用了属性,但它显示错误为     必须在非泛型静态类

中定义扩展方法
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 个答案:

答案 0 :(得分: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;
        }
    }