现有的答案很好;只是另一种观点:在许多情况下,最好使用 System.ComponentModel 而不是直接反射,因为这允许运行时属性场景 - 即 DataTable 的 DataView 如何将列公开为 properties。
性能方面 - 默认情况下,这在很大程度上是相同的,但如果您执行大量此操作(例如,批量数据导入/导出),您实际上可以使用这种方法获得显着的性能提升,由 HyperDescriptor 提供。
使用System.ComponentModel,代码大同小异:
static void Main()
{
object obj = new Customer { Address = new Address { ZipCode = "abcdef" } };
object address = GetValue(obj, "Address");
object zip = GetValue(address, "ZipCode");
Console.WriteLine(zip);
}
static object GetValue(object component, string propertyName)
{
return TypeDescriptor.GetProperties(component)[propertyName].GetValue(component);
}
这将为您提供与您使用数据绑定绑定到“Address.ZipCode”相同的处理方式(掩盖一些细节,如列表等)。
(请注意,如果您知道这是预期的类型,您可以将 zip 转换为字符串等)
要从深层路径(包括数据绑定使用的相同列表处理)中获取值,您可以使用以下内容:
static object ResolveValue(object component, string path) {
foreach(string segment in path.Split('.')) {
if (component == null) return null;
if(component is IListSource) {
component = ((IListSource)component).GetList();
}
if (component is IList) {
component = ((IList)component)[0];
}
component = GetValue(component, segment);
}
return component;
}
列表内容大致反映了常规数据绑定的行为(尽管它省略了一些内容,例如绑定上下文、货币管理器等)