如何使用C#返回标有自定义属性的枚举值

时间:2013-03-21 06:32:49

标签: c# enums custom-attributes

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

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
    }

将使用自定义属性标记的成员的值获取到List中的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

试试这个

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<int>使用此

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();