选择具有特定属性值的属性

时间:2015-09-28 05:44:04

标签: c# linq reflection

我正在寻找一种方法来在一个LINQ语句中选择具有特定值的特定自定义属性的属性。

我获得了具有我想要的属性的属性,但我不知道如何选择其特定值。

<AttributeUsage(AttributeTargets.Property)>
Public Class PropertyIsMailHeaderParamAttribute
    Inherits System.Attribute

    Public Property HeaderAttribute As String = Nothing
    Public Property Type As ParamType = Nothing

    Public Sub New()

    End Sub

    Public Sub New(ByVal headerAttribute As String, ByVal type As ParamType)
        Me.HeaderAttribute = headerAttribute
        Me.Type = type
    End Sub

    Public Enum ParamType
        base = 1
        open
        closed
    End Enum
    End Class


    private MsgData setBaseProperties(MimeMessage mailItem, string fileName)
    {
        var msgData = new MsgData();
        Type type = msgData.GetType();
        var props = from p in this.GetType().GetProperties()
                    let attr = p.GetCustomAttributes(typeof(Business.IT._21c.AddonFW.PropertyIsMailHeaderAttribute), true)
                    where attr.Length == 1
                    select new { Property = p, Attribute = attr.FirstOrDefault() as Business.IT._21c.AddonFW.PropertyIsMailHeaderAttribute };
    }

[解决]

var baseProps = from p in this.GetType().GetProperties()
                let attr = p.GetCustomAttribute<PropertyIsMailHeaderParamAttribute>()
                where attr != null && attr.Type == PropertyIsMailHeaderParamAttribute.ParamType.@base
select new { Property = p, Attribute = attr as Business.IT._21c.AddonFW.PropertyIsMailHeaderParamAttribute };

1 个答案:

答案 0 :(得分:5)

您必须将Attribute对象(使用常规强制转换或使用OfType<>扩展名)转换为您的类型,但最简单的方法是使用{{的通用版本1}}:

GetCustomAttribute<>