本文介绍了通过字符串获取字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过使用字符串作为变量名来获取对象字段的值.我试图通过反射来做到这一点:
I want to get the value of a field of an object by using a string as variable name.I tried to do this with reflection:
myobject.GetType().GetProperty("Propertyname").GetValue(myobject, null);
这很完美,但现在我想获得子属性"的值:
This works perfectly but now I want to get the value of "sub-properties":
public class TestClass1
{
public string Name { get; set; }
public TestClass2 SubProperty = new TestClass2();
}
public class TestClass2
{
public string Address { get; set; }
}
这里我想从 TestClass1
的对象中获取值 Address
.
Here I want to get the value Address
from a object of TestClass1
.
推荐答案
你已经做了你需要做的一切,你只需要做两次:
You already did everything you need to do, you just have to do it twice:
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);
这篇关于通过字符串获取字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!