2012-04-27 17 views
5

गुण कोडइनहेरिट की गई विशेषताओं

[AttributeUsage(AttributeTargets.Property, Inherited = true)] 
class IgnoreAttribute : Attribute 
{ 
} 

बेस वर्ग

abstract class ManagementUnit 
{ 
    [Ignore] 
    public abstract byte UnitType { get; } 
} 

मुख्य वर्ग

class Region : ManagementUnit 
{ 
    public override byte UnitType 
    { 
     get { return 0; } 
    } 

    private static void Main() 
    { 
     Type t = typeof(Region); 
     foreach (PropertyInfo p in t.GetProperties()) 
     { 
      if (p.GetCustomAttributes(typeof(IgnoreAttribute), true).Length != 0) 
       Console.WriteLine("have attr"); 
      else 
       Console.WriteLine("don't have attr"); 
     } 
    } 
} 

आउटपुट:don't have attr

बताएं कि यह क्यों हो रहा है? आखिरकार, इसे विरासत में मिला होना चाहिए।

उत्तर

5

विरासत ध्वज यह निर्धारित करता है कि विशेषता विरासत में प्राप्त की जा सकती है या नहीं। इस मान के लिए डिफ़ॉल्ट गलत है। हालांकि, यदि विरासत ध्वज सत्य पर सेट है, तो इसका अर्थ AllowMultiple ध्वज के मान पर निर्भर करता है। यदि विरासत ध्वज सत्य पर सेट किया गया है और AllowMultiple flag गलत है, तो विशेषता विरासत विशेषता को ओवरराइड कर देगी। हालांकि, यदि विरासत ध्वज सत्य पर सेट किया गया है और AllowMultiple ध्वज भी सत्य पर सेट किया गया है, तो विशेषता सदस्य पर जमा होती है।

http://aclacl.brinkster.net/InsideC/32ch09f.htm से चेक अध्याय निर्दिष्ट वंशानुक्रम गुण नियम

संपादित करें: जाँच Inheritance of Custom Attributes on Abstract Properties पहले उत्तर:

यह GetCustomAttributes() विधि है कि माता-पिता घोषणाओं पर गौर नहीं करता है। यह केवल निर्दिष्ट सदस्य पर लागू विशेषताओं को देखता है। https://msdn.microsoft.com/en-us/library/dwc6ew1d.aspx:

+3

नहीं है, के लिए डिफ़ॉल्ट "प्राप्त" सच है। https://msdn.microsoft.com/en-us/library/system.attributeusageattribute.inherited(v=vs.110).aspx – 00jt

0

PropertyInfo.GetCustomAttributes में विरासत ध्वज के रूप में द्वारा प्रलेखित दोनों गुण और घटनाओं के लिए नजरअंदाज कर दिया है। लेकिन आप संपत्तियों (या घटनाओं) की विरासत को सक्षम करने के लिए विशेषता में से एक का उपयोग कर सकते हैं। GETCustomAttributes ओवरलोड।

यह समस्या में और अधिक विस्तार से चर्चा की है: http://blog.seancarpenter.net/2012/12/15/getcustomattributes-and-overridden-properties/

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