gpt4 book ai didi

C# 使用反射获取通用对象(及其嵌套对象)的属性

转载 作者:太空狗 更新时间:2023-10-29 17:38:36 25 4
gpt4 key购买 nike

创建这个场景是为了帮助理解我想要实现的目标。

我正在尝试创建一个返回通用对象的指定属性的方法

例如

public object getValue<TModel>(TModel item, string propertyName) where TModel : class{
PropertyInfo p = typeof(TModel).GetProperty(propertyName);
return p.GetValue(item, null);
}

如果您正在寻找 TModel 项目 的属性,上面的代码可以正常工作例如

string customerName = getValue<Customer>(customer, "name");

但是,如果要找出客户的组名是什么,就成了一个问题:例如

string customerGroupName = getValue<Customer>(customer, "Group.name");

希望有人能给我一些关于这种出路方案的见解 - 谢谢。

最佳答案

这是一个使用递归来解决您的问题的简单方法。它允许您通过传递“带点”的属性名称来遍历对象图。它适用于属性和字段。

static class PropertyInspector 
{
public static object GetObjectProperty(object item,string property)
{
if (item == null)
return null;

int dotIdx = property.IndexOf('.');

if (dotIdx > 0)
{
object obj = GetObjectProperty(item,property.Substring(0,dotIdx));

return GetObjectProperty(obj,property.Substring(dotIdx+1));
}

PropertyInfo propInfo = null;
Type objectType = item.GetType();

while (propInfo == null && objectType != null)
{
propInfo = objectType.GetProperty(property,
BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.DeclaredOnly);

objectType = objectType.BaseType;
}

if (propInfo != null)
return propInfo.GetValue(item, null);

FieldInfo fieldInfo = item.GetType().GetField(property,
BindingFlags.Public | BindingFlags.Instance);

if (fieldInfo != null)
return fieldInfo.GetValue(item);

return null;
}
}

例子:

class Person
{
public string Name { get; set; }
public City City { get; set; }
}

class City
{
public string Name { get; set; }
public string ZipCode { get; set; }
}

Person person = GetPerson(id);

Console.WriteLine("Person name = {0}",
PropertyInspector.GetObjectProperty(person,"Name"));

Console.WriteLine("Person city = {0}",
PropertyInspector.GetObjectProperty(person,"City.Name"));

关于C# 使用反射获取通用对象(及其嵌套对象)的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2911719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com