2012-10-29 9 views
6

Eventuali duplicati:
How to get a list of properties with a given attribute?ottenere tutte le proprietà che ha un attributo personalizzato con valori specifici

Ho una classe personalizzata come questo

public class ClassWithCustomAttributecs 
{ 
    [UseInReporte(Use=true)] 
    public int F1 { get; set; } 

    public string F2 { get; set; } 

    public bool F3 { get; set; } 

    public string F4 { get; set; } 
} 

Ho un personalizzato attributo UseInReporte:

[System.AttributeUsage(System.AttributeTargets.Property ,AllowMultiple = true)] 
public class UseInReporte : System.Attribute 
{ 
    public bool Use; 

    public UseInReporte() 
    { 
     Use = false; 
    } 
} 

No Voglio ottenere Tutte le proprietà che ha [UseInReporte(Use=true)] come posso farlo utilizzando il riflesso?

grazie

risposta

11
List<PropertyInfo> result = 
    typeof(ClassWithCustomAttributecs) 
    .GetProperties() 
    .Where(
     p => 
      p.GetCustomAttributes(typeof(UseInReporte), true) 
      .Where(ca => ((UseInReporte)ca).Use) 
      .Any() 
     ) 
    .ToList(); 

Naturalmente typeof(ClassWithCustomAttributecs) dovrebbero essere sostituiti con un oggetto reale che si sta trattando.

+1

Non sono sicuro come questo gestisce '[UseInReporte (Use = true)]' –

+0

grazie caro amico. Come posso ottenere le proprietà con 'Use == true'? – Arian

+0

@JonB, buon punto, grazie. Aggiornamento della risposta – Andrei

Problemi correlati