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

Jim*_*mbo 9 c# generics reflection types properties

这是一个场景,旨在帮助理解我想要实现的目标.

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

例如

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

该代码,如果你正在寻找的一个属性以上正常工作TModel item

string customerName = getValue<Customer>(customer, "name");
Run Code Online (Sandbox Code Playgroud)

但是,如果您想知道客户的组名是什么,那就成了一个问题:例如

string customerGroupName = getValue<Customer>(customer, "Group.name");
Run Code Online (Sandbox Code Playgroud)

希望有人可以给我一些关于这种情况的见解 - 谢谢.

Phi*_*ert 11

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

例:

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"));
Run Code Online (Sandbox Code Playgroud)


Gui*_*e86 3

在 System.Web.UI 命名空间中,有一个方法可以做到这一点:

DataBinder.Eval(source, expression);
Run Code Online (Sandbox Code Playgroud)

  • 我很担心 - 为什么它在 System.Web.UI 中? (2认同)