如何通过传递枚举值和属性类型来获取枚举的自定义属性?

问题描述 投票:0回答:1

有很多在线示例,这些示例创建一个枚举扩展方法,该方法以枚举值作为参数,并且在该方法中获取特定属性,例如:

namespace MVVMProj.ProjUtilities
{
  public class EnumerationHelpers
  {
    public static string GetStatusText(this Enum value)
    {
      var type = value.GetType();

      string name = Enum.GetName(type, value);
      if (name == null) { return null; }

      var field = type.GetField(name);
      if (field == null) { return null; }

      var attr = Attribute.GetCustomAttribute(field, typeof(StatusTextAttribute)) as StatusTextAttribute;
      if (attr == null) { return null; }

      return attr.StatusText;
    }
  }
}

我想知道的是,有没有一种方法也可以将属性类型传递给该方法,所以我不需要为每个不同的属性继续编写特定的方法?

这还没有完成,但是,它应该使您了解我要实现的目标:

namespace MVVMProj.ProjUtilities
{
  public class EnumerationHelpers
  {
    public static string GetCustomAttribute(this Enum value, Type customAttr) 
             //Or instead of passing a Type, a string of the attribute's name
    {
      var type = value.GetType();

      string name = Enum.GetName(type, value);
      if (name == null) { return null; }

      var field = type.GetField(name);
      if (field == null) { return null; }

      var attr = Attribute.GetCustomAttribute(field, ....) as ....;
      if (attr == null) { return null; }

      return attr....;
    }
  }
}

我想我也不能只返回一个字符串,因为它可以是任何数据类型。

也许是一些通用方法?

任何建议将不胜感激!

编辑:用法:

它遍历枚举,创建了一个字典,所以我可以在组合框中显示值。仅当属性与if语句中的条件匹配时,才添加项目。

还要注意的一件事是,定制属性也是一个枚举。

[Aybe:'item'只是迭代中的一个对象,所以我进行了强制转换。尽管我在if语句中遇到错误,但它试图将CaseTypeAttribute与实际的CaseType枚举值进行比较,我需要怎么做才能解决?

错误:严重性代码说明项目文件行抑制状态错误CS0019运算符'=='无法应用于类型'SBC.CaseTypeAttribute'和'SBC.CaseType'的操作数

private Dictionary<int, string> _substancetypes;
public Dictionary<int, string> SubstanceTypes
{
  get
  {
    if (_substancetypes == null)
    {
      _substancetypes = new Dictionary<int, string>();
      foreach (var item in Enum.GetValues(typeof(SBC.SubstanceTypeCode)))
      {
        var descriptionAttribute = ((SBC.SubstanceTypeCode)item).GetAttribute<SBC.CaseTypeAttribute>();
        if (descriptionAttribute != null && 
               descriptionAttribute == SBC.CaseType.Exposures) //Error here
        {
          _substancetypes.Add((int)item, CTS_MVVM.CTS_Utilities.EnumerationHelpers.GetDescriptionFromEnumValue((SBC.SubstanceTypeCode)item));
        }
      }
    }

    return _substancetypes;
  }
}

有很多在线示例,其中创建了一个枚举扩展方法,该方法以枚举值作为参数,并且在该方法中获得了特定的属性,例如:namespace MVVMProj.ProjUtilities {...

c# enums custom-attributes
1个回答
2
投票

这样的事情?

© www.soinside.com 2019 - 2024. All rights reserved.