我想通过使用字符串作为变量名来获取对象字段的值.我尝试用反射做到这一点:
myobject.GetType().GetProperty("Propertyname").GetValue(myobject, null);
Run Code Online (Sandbox Code Playgroud)
这很好用,但现在我想得到"子属性"的值:
public class TestClass1
{
public string Name { get; set; }
public TestClass2 SubProperty = new TestClass2();
}
public class TestClass2
{
public string Address { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在这里,我想Address从一个对象中获取值TestClass1.
Dir*_*irk 15
你已经做了你需要做的一切,你只需要做两次:
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);
Run Code Online (Sandbox Code Playgroud)
尝试
myobject.GetType().GetProperty("SubProperty").GetValue(myobject, null)
.GetType().GetProperty("Address")
.GetValue(myobject.GetType().GetProperty("SubProperty").GetValue(myobject, null), null);
Run Code Online (Sandbox Code Playgroud)
您的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);
}
}
Run Code Online (Sandbox Code Playgroud)
为了在您的上下文中获得所需的值,只需执行以下代码行。
class Program
{
static void Main()
{
var t1 = new TestClass1();
Console.WriteLine(new SubMember<string>(t1, "SubProperty", "Address").Value);
}
}
Run Code Online (Sandbox Code Playgroud)
这将为您提供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);
}
}
Run Code Online (Sandbox Code Playgroud)
该类现在允许您从初始类中提取属性,并从从第一个属性中提取的第二个属性中获取值。