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; }
}

在这里,我想AddressTestClass1.

4

3 回答 3

19

你已经做了所有你需要做的事情,你只需要做两次:

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 回答
5

您的SubProperty成员实际上是 aField而不是 a Property,这就是为什么您无法使用该GetProperty(string)方法访问它的原因。在您当前的场景中,您应该使用以下类首先获取SubProperty字段,然后获取Address属性。

此类将允许您通过关闭T具有适当类型的类型来指定属性的返回类型。然后,您只需将要提取其成员的对象添加到第一个参数中。第二个参数是您要提取的字段的名称,而第三个参数是您要获取其值的属性的名称。

class SubMember<T>
{
    public T Value { get; set; }

    public SubMember(object source, string field, string property)
    {
        var fieldValue = source.GetType()
                               .GetField(field)
                               .GetValue(source);

        Value = (T)fieldValue.GetType()
                             .GetProperty(property)
                             .GetValue(fieldValue, null);
    }
}

为了在您的上下文中获得所需的值,只需执行以下代码行。

class Program
{
    static void Main()
    {
        var t1 = new TestClass1();

        Console.WriteLine(new SubMember<string>(t1, "SubProperty", "Address").Value);            
    }
}

这将为您提供Address属性中包含的值。只要确保您首先为所述属性添加一个值。

但是,如果您真的想将类的字段更改为属性,那么您应该对原始SubMember类进行以下更改。

class SubMemberModified<T>
{
    public T Value { get; set; }

    public SubMemberModified(object source, string property1, string property2)
    {
        var propertyValue = source.GetType()
                                  .GetProperty(property1)
                                  .GetValue(source, null);

        Value = (T)propertyValue.GetType()
                                .GetProperty(property2)
                                .GetValue(propertyValue, null);
    }
}

此类现在将允许您从初始类中提取属性,并从从第一个属性中提取的第二个属性中获取值。

于 2013-06-03T23:15:14.470 回答
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 回答