简体   繁体   English

通过反射从通用对象属性获取价值

[英]Get value from a generic object property by reflection

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 -因此重要的是要说每个主要标识符都具有[Audite]属性

edit 编辑
The type of ? 的类型 is the type of a Property of genericObject. 是genericObject的属性的类型。 example: 例:
Department is genericObject. 部门是genericObject。
Manager is a property. 经理是财产。 So in this case I want element.GetValue( ? , null).ToString(); 因此,在这种情况下,我需要element.GetValue( ? , null).ToString(); where this element is a declared in Manager class as: 该元素在Manager类中声明为:

 [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. 这使用@ liho1eye的解决方案,我刚刚添加了一个空引用验证,这给我带来了一些问题。

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

那将是您的对象的实例

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

Should be your genericObject . 应该是您的genericObject

As far as I can compile-it-in-mind, you are iterating thru the properties of genericObject only. 据我所知,您仅通过genericObject的属性进行迭代。 Identifying properties that have 'AuditeAttribute', and then getting it's value. 识别具有“ AuditeAttribute”的属性,然后获取其值。

See MSDN for complete details 有关完整的详细信息,请参见MSDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM