我需要获取每个对象的所有属性的名称和值。其中一些是引用类型,所以如果我得到以下对象:
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
语句中,我只检查属性是否在我的引用类型的命名空间下,如果是,我应该获取所有嵌套的属性值,但这就是引发异常的地方。