【问题标题】:Extension method must be defined in a non-generic static class in c# [duplicate]扩展方法必须在c#中的非泛型静态类中定义[重复]
【发布时间】:2014-10-31 01:58:55
【问题描述】:

我尝试使用带有字符串值的枚举,因为我使用 Attribute 但它显示错误为 扩展方法必须定义在非泛型静态类中

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;
    }

}

【问题讨论】:

  • 那么有什么问题。为什么不将扩展方法移动到另一个类?

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


【解决方案1】:

你必须将你的方法移动到一个静态类

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;
        }
    }

【讨论】:

    猜你喜欢
    • 2023-03-10
    • 2016-10-25
    • 1970-01-01
    • 2012-01-01
    • 2014-12-23
    相关资源
    最近更新 更多