2015-09-28 114 views
1

我正在尋找一種方法來選擇在單個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 == [email protected] 
select new { Property = p, Attribute = attr as Business.IT._21c.AddonFW.PropertyIsMailHeaderParamAttribute }; 
+0

是不是第一類的代碼,VB.NET中的PropertyIsMailHeaderParamAttribute? –

+0

是的,我們的庫是用VB.NET編寫的,這是我從中獲得CustomAttribute的地方。不要問爲什麼..犯了錯誤。如果你們想知道的話,我也改變了這些類的名字。 – OhSnap

回答

3

您可能已投下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; 
+0

謝謝你。這幫了我很多: – OhSnap

相關問題