2012-10-29 38 views
6
साथ एक कस्टम विशेषता है कि जाओ

संभव डुप्लिकेट:
How to get a list of properties with a given attribute?सभी गुण विशिष्ट मान

मैं इस

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; } 
} 

मैं एक कस्टम है की तरह एक कस्टम वर्ग है विशेषता UseInReporte:

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

    public UseInReporte() 
    { 
     Use = false; 
    } 
} 

नहीं, मैं उन सभी गुणों को प्राप्त करना चाहता हूं जिनमें [UseInReporte(Use=true)] है कि मैं प्रतिबिंब का उपयोग करके यह कैसे कर सकता हूं?

धन्यवाद

उत्तर

11
List<PropertyInfo> result = 
    typeof(ClassWithCustomAttributecs) 
    .GetProperties() 
    .Where(
     p => 
      p.GetCustomAttributes(typeof(UseInReporte), true) 
      .Where(ca => ((UseInReporte)ca).Use) 
      .Any() 
     ) 
    .ToList(); 
पाठ्यक्रम typeof(ClassWithCustomAttributecs) के

एक वास्तविक वस्तु आप के साथ काम कर रहे हैं के साथ प्रतिस्थापित किया जाना चाहिए।

+1

यह सुनिश्चित नहीं है कि यह कैसे प्रबंधित करता है [UseInReporte (उपयोग = सत्य)] ' –

+0

धन्यवाद प्रिय मित्र। मैं '= = सही 'का उपयोग करके गुण कैसे प्राप्त कर सकता हूं? – Arian

+0

@ जोनबी, अच्छा बिंदु, धन्यवाद। उत्तर – Andrei

संबंधित मुद्दे