Get value from a generic object property by reflec

2019-06-11 10:00发布

问题:

I just want to get main identifier from all domain object from a generic property.
The code until now:

IEnumerable<PropertyInfo> customProperties = genericObject.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

foreach (PropertyInfo justAuditElementProperties in customProperties) {

    IEnumerable<PropertyInfo> elementsToAudit = justAuditElementProperties.PropertyType.GetProperties().Where(p => Attribute.IsDefined(p, typeof (AuditeAttribute)));
    foreach (PropertyInfo element in elementsToAudit) {
        string name = justAuditElementProperties.PropertyType.FullName + "." + element.Name;
        string value = element.GetValue( ? , null).ToString();
        atributoNomeValor.Add(name, value);
    }
}

What's the correct replacement to ?

-- So is important to say that every main identifier has [Audite] attribute

edit
The type of ? is the type of a Property of genericObject. example:
Department is genericObject.
Manager is a property. So in this case I want element.GetValue( ? , null).ToString(); where this element is a declared in Manager class as:

 [Audite]
 public string name { get; set; }

Solution
This use the solution from @liho1eye, I just added a null reference verification, that generate some problems for me.

var propertyParent = justAuditElementProperties.GetValue(genericObject, null);
string value = propertyParent != null ? element.GetValue(propertyParent, null).ToString() : "";

回答1:

that would be the instance of your object

string value = element.GetValue(justAuditElementProperties.GetValue(genericObject, null), null).ToString();


回答2:

Should be your genericObject.

As far as I can compile-it-in-mind, you are iterating thru the properties of genericObject only. Identifying properties that have 'AuditeAttribute', and then getting it's value.

See MSDN for complete details