2013-05-26 149 views
12

我想通过使用字符串作为变量名称来获取对象字段的值。 我试着用反射来做到这一点:通过字符串获取字段值

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的对象。

回答

10

你已经做了你需要做的一切,你就必须做两次:

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); 
3

尝试

myobject.GetType().GetProperty("SubProperty").GetValue(myobject, null) 
.GetType().GetProperty("Address") 
.GetValue(myobject.GetType().GetProperty("SubProperty").GetValue(myobject, null), null); 
2

SubProperty成员实际上是一个Field而不是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); 
    } 
} 

这个班的学生将允许您从您最初的类中提取属性,并从第二个属性,这是从第一特性提取的值。