我需要获取每个对象的所有属性的名称和值。其中有些是引用类型,所以如果我得到以下对象:
public class Artist {
public int Id { get; set; }
public string Name { get; set; }
}
public class Album {
public string AlbumId { get; set; }
public string Name { get; set; }
public Artist AlbumArtist { get; set; }
}当从Album对象获取属性时,我还需要获得嵌套的属性AlbumArtist.Id和AlbumArtist.Name的值。
到目前为止,我有以下代码,但是当尝试获取嵌套代码的值时,它会触发System.Reflection.TargetException。
var valueNames = new Dictionary<string, string>();
foreach (var property in row.GetType().GetProperties())
{
if (property.PropertyType.Namespace.Contains("ARS.Box"))
{
foreach (var subProperty in property.PropertyType.GetProperties())
{
if(subProperty.GetValue(property, null) != null)
valueNames.Add(subProperty.Name, subProperty.GetValue(property, null).ToString());
}
}
else
{
var value = property.GetValue(row, null);
valueNames.Add(property.Name, value == null ? "" : value.ToString());
}
}因此,在If语句中,我只是检查属性是否位于我的引用类型的命名空间之下,如果是的话,我应该获得所有嵌套的属性值,但这就是引发异常的地方。
发布于 2012-09-19 14:45:47
这失败是因为您试图在一个Artist实例上获取一个PropertyInfo属性:
if(subProperty.GetValue(property, null) != null)
valueNames.Add(subProperty.Name, subProperty.GetValue(property, null).ToString());据我所知,您需要来自Artist实例的值,该实例嵌套在row对象(这是一个Album实例)内。
所以你应该改变这一点:
if(subProperty.GetValue(property, null) != null)
valueNames.Add(subProperty.Name, subProperty.GetValue(property, null).ToString());对此:
var propValue = property.GetValue(row, null);
if(subProperty.GetValue(propValue, null) != null)
valueNames.Add(subProperty.Name, subProperty.GetValue(propValue, null).ToString());Full (在不需要的情况下,只需稍作更改,以避免调用GetValue )
var valueNames = new Dictionary<string, string>();
foreach (var property in row.GetType().GetProperties())
{
if (property.PropertyType.Namespace.Contains("ATG.Agilent.Entities"))
{
var propValue = property.GetValue(row, null);
foreach (var subProperty in property.PropertyType.GetProperties())
{
if(subProperty.GetValue(propValue, null) != null)
valueNames.Add(subProperty.Name, subProperty.GetValue(propValue, null).ToString());
}
}
else
{
var value = property.GetValue(row, null);
valueNames.Add(property.Name, value == null ? "" : value.ToString());
}
}此外,您可能会遇到重复属性名称的情况,因此您的IDictionary<,>.Add将失败。我建议在这里用更可靠的名字命名。
例如:property.Name + "." + subProperty.Name
https://stackoverflow.com/questions/12496791
复制相似问题