c# - 枚举扩展方法未显示

标签 c# enums

我正在尝试为枚举添加新的/扩展方法,但扩展方法未显示在智能感知方法列表中。请帮助这是我的代码。

扩展名:

public static class EnumExtensions
    {
        public static string GetDescriptionAttr(this Enum value,string key)
        {
            var type = value.GetType();
            var memInfo = type.GetMember(key);
            var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),
                false);
            var description = ((DescriptionAttribute)attributes[0]).Description;
            return description;
        }
    }

试图调用其他类的结果(调用者和扩展都在同一个项目中)

enter image description here

最佳答案

扩展方法只能应用于实例

public static class EnumExtensions {
  // This extension method requires "value" argument
  // that should be an instance of Enum class 
  public static string GetDescriptionAttr(this Enum value, string key) {
    ...
  }
}

...

public enum MyEnum {
  One, 
  Two,
  Three
}

Enum myEnum = MyEnum.One;

// You can call extension method on instance (myEnum) only
myEnum.GetDescriptionAttr("One");

关于c# - 枚举扩展方法未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22189872/

相关文章:

c# - 如何通过 GPS 检查距 x,y 位置 10 米的半径

c# - 无法将 MyType<T> 转换为 MyType<object>

c# - 如何对 OwnsMany 集合进行分页?

ruby-on-rails - Rails 中的枚举 : uppercase or lowercase?

c# - 使用初始化器循环遍历枚举会产生意想不到的结果

c# - 如何使用枚举填充组合框 - 在组合框中显示枚举的整数(值)

c# - 无法让 System.Web.Optimization 与 Nancy Self Hosting 一起运行

c# - BindablePicker 的 SelectedItem 在 MvvmCross + xamarin 表单中的 Bindable stackLayout 中不起作用

c++ - 枚举作为具有返回值的类成员函数

postgresql:枚举和字符变化,更新