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

効果的には、私はそれを取り戻す...私はフィールドを見つけることはできません1と2を取得することができます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の権利を、それが実際には右の彼らに "IsSomething" ブールのトンを持っているIsLiteral

+0

ええ、それはあまりにも遅く実現しました。 – deostroll

+0

DataDinkの答えは、実際には少しスムーズです。はい; && info.IsStaticを追加してみてください。 –

+0

両方が真であれば、IsLiteralとIsStaticの違いは何ですか? – deostroll

5

のFieldInfoオブジェクトを使用してスムーズなのですとにかく属性をチェックする上で大量のコードが必要です。

関連する問題