2017-01-05 2 views
4

まず、私の悪い英語をお詫びします...私はあなたが私が言いたいことを理解することを願っています。SubClassesでPropertyInfoのC#GetValue

私はクラスのプロパティの値を取得する必要がある小さなコードに問題があります。 (。。それは私の完全なプロジェクトが、私は何をしたいのかという概念はありませんそして、この単純なコードで、私がブロックされています)

コードがあります:(このサンプルでは正常に動作します。)

using System; 
using System.Reflection; 

class Example 
{ 
    public static void Main() 
    { 
     test Group = new test(); 
     BindingFlags bindingFlags = BindingFlags.Public | 
            BindingFlags.NonPublic | 
            BindingFlags.Instance | 
            BindingFlags.Static; 
     Group.sub.a = "allo"; 
     Group.sub.b = "lol"; 

     foreach (PropertyInfo property in Group.GetType().GetField("sub").FieldType.GetProperties(bindingFlags)) 
     { 
      string strName = property.Name; 
      Console.WriteLine(strName + " = " + property.GetValue(Group.sub, null).ToString()); 
      Console.WriteLine("---------------"); 
     } 
    } 
} 

public class test 
{ 
    public test2 sub = new test2(); 
} 

public class test2 
{ 
    public string a { get; set; } 
    public string b { get; set; } 
} 

しかし、私はGroup.subforeachのような動的アクセスに置き換えたいと思っています(GetField(Var)と同じです)。私はたくさんの組み合わせを試しましたが、解決策は見つかりませんでした。

property.GetValue(property.DeclaringType, null) 

または

property.GetValue(Group.GetType().GetField("sub"), null) 

または

property.GetValue(Group.GetType().GetField("sub").FieldType, null) 

だから私はあなたが理解だと思います。オブジェクトGroup.subのインスタンスを動的に与えたいと思います。私のフルプロジェクトでは、たくさんのサブクラスがあるからです。

アイデア?

答えて

3

あなたはすでにあなたがその値を取得し、それを保持する必要があります、Group.GetType().GetField("sub")を使用してsubフィールドにアクセスしている:あなたの応答をEvenhuis:

FieldInfo subField = Group.GetType().GetField("sub"); 

// get the value of the "sub" field of the current group 
object subValue = subField.GetValue(Group); 
foreach (PropertyInfo property in subField.FieldType.GetProperties(bindingFlags)) 
{ 
    string strName = property.Name; 
    Console.WriteLine(strName + " = " + property.GetValue(subValue, null).ToString());  
} 
+0

はあなたにCをありがとうございました。それはまさに私がやりたいことです! 私はテストして動作します。 追加レベルで同じことを行うには、そのようにすることはできますか? FieldInfo subField = Group.GetType()。GetField( "sub"); オブジェクトsubValue = subField.GetValue(Group); FieldInfo subField2 = Group.GetType()。GetField( "sub")。FieldType.GetField( "sub2"); オブジェクトsubValue2 = subField2.GetValue(subValue); さらに高速な方法が存在しますか? –

+1

ええ、あなたは以前の結果に「ホールド」することができます。 "sub2"フィールド情報を取得するには、 'Group.GetType()...'で始める必要はありません。 'subField.FieldType.GetField(" sub2 ")'を使うことができます。 –

+0

C.Evenhuisありがとうございます。私はそれを好きだった=) –

関連する問題