簡體   English   中英

選擇具有特定屬性值的屬性

[英]Select properties with specific attribute value

我正在尋找一種方法來選擇具有特定自定義屬性和單個 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 };

您要么必須將Attribute對象(使用常規轉換或例如使用OfType<>擴展)轉換為您的類型,但最簡單的方法是使用GetCustomAttribute<>的通用版本:

var props = from p in this.GetType().GetProperties()
            let attr = p.GetCustomAttribute<PropertyIsMailHeaderAttribute>()
            where attr != null && attr.HeaderAttribute == "FooBar"
                               && attr.Type = ParamType.open
            select whatever;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM