【问题标题】:How to return enum's values marked with custom attribute using C#如何使用 C# 返回标有自定义属性的枚举值
【发布时间】:2013-03-21 06:32:48
【问题描述】:

我有一个枚举,其中一些成员由自定义属性标记,例如:

public enum VideoClipTypeEnum : int
{
    Exhibitions = 1,

    TV = 2,

    [ClipTypeDisplayAttribute(false)]
    Content = 3
}

我的属性是:

public class ClipTypeDisplayAttribute : DescriptionAttribute
    {
        #region Private Variables

        private bool _treatAsPublicType;

        #endregion

        #region Ctor

        public ClipTypeDisplayAttribute(bool treatAsPublicType)
        {
            _treatAsPublicType = treatAsPublicType;
        }

        #endregion

        #region Public Props

        public bool TreatAsPublicType
        {
            get
            {
                return _treatAsPublicType;
            }
            set
            {
                _treatAsPublicType = value;
            }
        }

        #endregion
    }

将用我的自定义属性标记的成员的值放入列表的最佳方法是什么?

【问题讨论】:

  • 你能说得更具体点吗?您的示例中没有字段-您是在谈论枚举成员吗?您是否只想接收带有属性标记的枚举成员?
  • 没错!成员...对不起那个陷阱)

标签: c# enums custom-attributes


【解决方案1】:

试试这个

var values = 
    from f in typeof(VideoClipTypeEnum).GetFields()
    let attr = f.GetCustomAttributes(typeof(ClipTypeDisplayAttribute))
                .Cast<ClipTypeDisplayAttribute>()
                .FirstOrDefault()
    where attr != null
    select f;

这实际上将返回FieldInfo 作为枚举值。要获取原始值,请尝试此操作。

var values = 
    ... // same as above
    select (VideoClipTypeEnum)f.GetValue(null);

如果您还想按属性的某些属性进行过滤,您也可以这样做。像这样

var values = 
    ... // same as above
    where attr != null && attr.TreatAsPublicType
    ... // same as above

注意:这是因为枚举值(例如VideoClipTypeEnum.TV)实际上在内部实现为VideoClipTypeEnum 的静态常量字段。

要获得List&lt;int&gt;,请使用此

var values = 
    (from f in typeof(VideoClipTypeEnum).GetFields()
     let attr = f.GetCustomAttributes(typeof(ClipTypeDisplayAttribute))
                 .Cast<ClipTypeDisplayAttribute>()
                 .FirstOrDefault()
     where attr != null
     select (int)f.GetValue(null))
    .ToList();

【讨论】:

  • 谢谢!但是如果我需要获取值的 List 怎么办?我需要该列表来过滤我的 repo 中的 videoClips。
  • GetCustomAttributes&lt;T&gt;() 是一个扩展,它包含了您的两个步骤并使其更具可读性,IMO。
  • @Damien_The_Unbeliever 似乎只在 4.5 中可用,但很高兴知道。
猜你喜欢
  • 1970-01-01
  • 2011-07-03
  • 2017-04-02
  • 2016-02-21
  • 2017-06-04
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多