2009-04-10 19 views

答えて

595

反射;

obj.GetType().GetProperties(); 

タイプのため:例えば

typeof(Foo).GetProperties(); 

class Foo { 
    public int A {get;set;} 
    public string B {get;set;} 
} 
... 
Foo foo = new Foo {A = 1, B = "abc"}; 
foreach(var prop in foo.GetType().GetProperties()) { 
    Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null)); 
} 

フィードバックに続き...

  • のvalを取得するために、例えば、静的プロパティのueは、を最初の引数としてGetValue
  • に渡します。非公開のプロパティを調べるには、たとえばGetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)(すべてのpublic/privateインスタンスのプロパティを返します)を使用します。
+8

としての答えの1をマークしてください、またTypeDescriptor.GetPropertiesによって公開さComponentModel、(...)があります時間)。 –

+4

提案:保護された/私的/静的/継承されたプロパティをカバーするための答えを展開してください。 – Richard

+1

あなたが表示するforeach文は、あなたがクラスのプロパティを取得したいクラス内からでも機能します:) –

6

リフレクションを使用できます。

Type typeOfMyObject = myObject.GetType(); 
PropertyInfo[] properties =typeOfMyObject.GetProperties(); 
52

あなたがこれを行うにリフレクションを使用することができます。 を(私のライブラリから - これは名前と値を取得します)

public static Dictionary<string, object> DictionaryFromType(object atype) 
    { 
     if (atype == null) return new Dictionary<string, object>(); 
     Type t = atype.GetType(); 
     PropertyInfo[] props = t.GetProperties(); 
     Dictionary<string, object> dict = new Dictionary<string, object>(); 
     foreach (PropertyInfo prp in props) 
     { 
      object value = prp.GetValue(atype, new object[]{}); 
      dict.Add(prp.Name, value); 
     } 
     return dict; 
    } 

この事は、インデックス付きプロパティのために動作しません - そのために(扱いにくいってきている):

public static Dictionary<string, object> DictionaryFromType(object atype, 
    Dictionary<string, object[]> indexers) 
{ 
    /* replace GetValue() call above with: */ 
    object value = prp.GetValue(atype, ((indexers.ContainsKey(prp.Name)?indexers[prp.Name]:new string[]{}); 
} 

また、唯一のパブリックプロパティを取得する:(see MSDN on BindingFlags enumを)

/* replace */ 
PropertyInfo[] props = t.GetProperties(); 
/* with */ 
PropertyInfo[] props = t.GetProperties(BindingFlags.Public) 

これは匿名型でも機能します。

public static string[] PropertiesFromType(object atype) 
    { 
     if (atype == null) return new string[] {}; 
     Type t = atype.GetType(); 
     PropertyInfo[] props = t.GetProperties(); 
     List<string> propNames = new List<string>(); 
     foreach (PropertyInfo prp in props) 
     { 
      propNames.Add(prp.Name); 
     } 
     return propNames.ToArray(); 
    } 

をそして、それはちょうどちょうど値に対してほぼ同じだ、またはあなたが使用することができます:
は名前だけを取得するには

GetDictionaryFromType().Keys 
// or 
GetDictionaryFromType().Values 

をしかし、それは少し遅く、私は想像です。

+0

... atype.GetProperty(prp.Name)はprpを返すでしょうか? –

+0

ああ - そうだよ! D'oh。 –

+0

私は今それを修正しました。 –

19

あなたはType.GetProperties() mehodでSystem.Reflection名前空間を使用することができます。私も要件のこの種の直面しています

PropertyInfo[] propertyInfos; 
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public|BindingFlags.Static); 
2

私は別のアイデアを持って、この議論から、

Obj.GetType().GetProperties()[0].Name 

これはまた、プロパティ名を示しています。

Obj.GetType().GetProperties().Count(); 

これはプロパティの数を示します。

ありがとうございます。これはいい話です。

29
public List<string> GetPropertiesNameOfClass(object pObject) 
{ 
    List<string> propertyList = new List<string>(); 
    if (pObject != null) 
    { 
     foreach (var prop in pObject.GetType().GetProperties()) 
     { 
      propertyList.Add(prop.Name); 
     } 
    } 
    return propertyList; 
} 

この機能は、クラスプロパティのリストを取得するための機能です。ここで

public class MyObject 
{ 
    public string value1 { get; set; } 
    public string value2 { get; set; } 

    public PropertyInfo[] GetProperties() 
    { 
     try 
     { 
      return this.GetType().GetProperties(); 
     } 
     catch (Exception ex) 
     { 

      throw ex; 
     } 
    } 

    public PropertyInfo GetByParameterName(string ParameterName) 
    { 
     try 
     { 
      return this.GetType().GetProperties().FirstOrDefault(x => x.Name == ParameterName); 
     } 
     catch (Exception ex) 
     { 

      throw ex; 
     } 
    } 

    public static MyObject SetValue(MyObject obj, string parameterName,object parameterValue) 
    { 
     try 
     { 
      obj.GetType().GetProperties().FirstOrDefault(x => x.Name == parameterName).SetValue(obj, parameterValue); 
      return obj; 
     } 
     catch (Exception ex) 
     { 
      throw ex; 
     } 
    } 
} 
+5

これを変更して 'yield return'を使うとよいでしょう。大したことではありませんが、それを実行するより良い方法です。 –

+1

私はこれが好きです。なぜなら、* reflection *という単語を含まない唯一の答えだからです。 –

+4

しかし、これはまだ**反射を使用しています。 – GGG

5

は@lucasjonesが答える改善されています。私は彼の答えの後にコメント欄で述べた改善を加えました。私は誰かがこれを役に立つと願っています。

public static string[] GetTypePropertyNames(object classObject, BindingFlags bindingFlags) 
{ 
    if (classObject == null) 
    { 
     throw new ArgumentNullException(nameof(classObject)); 
    } 

     var type = classObject.GetType(); 
     var propertyInfos = type.GetProperties(bindingFlags); 

     return propertyInfos.Select(propertyInfo => propertyInfo.Name).ToArray(); 
} 
2

私のソリューションです

5

@ MarcGravellの回答に基づいて、ここにはUnity C#で動作するバージョンがあります。 (反射は、コンパイル時に固定され、動的実行時プロパティを可能に -

ObjectsClass foo = this; 
foreach(var prop in foo.GetType().GetProperties()) { 
    Debug.Log("{0}={1}, " + prop.Name + ", " + prop.GetValue(foo, null)); 
} 
関連する問題