2009-08-20 12 views
7

संभव डुप्लिकेट:
Type.GetFields() - only returning “public const” fieldsको दर्शाते हुए लगातार गुण/.net में खेतों

मैं एक वर्ग है जो इस प्रकार की तरह लग रहा है:

public class MyConstants 
{ 
    public const int ONE = 1; 
    public const int TWO = 2; 

    Type thisObject; 
    public MyConstants() 
    { 
     thisObject = this.GetType(); 
    } 

    public void EnumerateConstants() 
    { 
     PropertyInfo[] thisObjectProperties = thisObject.GetProperties(BindingFlags.Public); 
     foreach (PropertyInfo info in thisObjectProperties) 
     { 
      //need code to find out of the property is a constant 
     } 
    } 
} 

Bascially यह कोशिश कर रहा है को प्रतिबिंबित करने के अपने आप। मुझे पता है कि फील्ड वन, & TWO को कैसे प्रतिबिंबित किया जाए। लेकिन मुझे कैसे पता चलेगा कि यह स्थिर है या नहीं?

+4

प्रभावी रूप से http://stackoverflow.com/questions/1287797 –

+0

का डुप्लिकेट मैं इसे वापस लेता हूं ... मुझे फ़ील्ड एक और दो नहीं मिल रहा है। – deostroll

+0

वे सिर्फ फ़ील्ड नहीं हैं, वे स्थिर फ़ील्ड हैं, उदाहरण फ़ील्ड नहीं। –

उत्तर

16

ऐसा इसलिए है क्योंकि वे फ़ील्ड हैं, गुण नहीं। प्रयास करें:

public void EnumerateConstants() {   
     FieldInfo[] thisObjectProperties = thisObject.GetFields(); 
     foreach (FieldInfo info in thisObjectProperties) { 
      if (info.IsLiteral) { 
       //Constant 
      } 
     }  
    } 

संपादित करें:

var m = new object(); 
foreach (var f in m.GetType().GetFields()) 
if (f.IsLiteral) 
{ 
    // stuff 
} 

आप एक छोटे से बचाता है कौन सा: DataDink के अधिकार, इसका इस्तेमाल करने के IsLiteral

+0

ओह हाँ इसे बहुत देर हो गई ... हाँ कुछ भी अनिवार्य रूप से स्थिर भी है? – deostroll

+0

डेटाडिंक का जवाब वास्तव में थोड़ा आसान है। और हाँ; & info.IsStatic जोड़ने का प्रयास करें। –

+0

यदि दोनों सत्य हैं तो IsLiteral और IsStatic के बीच अंतर क्या है? – deostroll

5

FieldInfo वस्तुओं वास्तव में उन पर सही "IsSomething" बूलियन्स की एक टन है चिकनी है वैसे भी गुणों की जांच करने के लिए कोड की राशि।

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