27

文字列を変数名として使用して、オブジェクトのフィールドの値を取得したいと考えています。私は反射でこれをやろうとしました:

myobject.GetType().GetProperty("Propertyname").GetValue(myobject, null);

これは完全に機能しますが、「サブプロパティ」の値を取得したいと思います:

public class TestClass1
{
    public string Name { get; set; }
    public TestClass2 SubProperty = new TestClass2();
}

public class TestClass2
{
    public string Address { get; set; }
}

Addressここでは、 のオブジェクトから値を取得したいと考えていますTestClass1

4

3 に答える 3

19

必要な作業はすべて完了しています。あとは 2 回行うだけです。

TestClass1 myobject = ...;
// get SubProperty from TestClass1
TestClass2 subproperty = (TestClass2) myobject.GetType()
    .GetProperty("SubProperty")
    .GetValue(myobject, null);
// get Address from TestClass2
string address = (string) subproperty.GetType()
    .GetProperty("Address")
    .GetValue(subproperty, null);
于 2013-05-26T15:30:16.917 に答える
4

試す

 myobject.GetType().GetProperty("SubProperty").GetValue(myobject, null)
 .GetType().GetProperty("Address")
 .GetValue(myobject.GetType().GetProperty("SubProperty").GetValue(myobject, null), null);
于 2013-05-26T15:30:53.680 に答える