c# - 在嵌套属性中使用 GetValue() 在反射中抛出 TargetException

标签 c# .net reflection

我需要获取每个对象的所有属性的名称。其中一些是引用类型,所以如果我得到以下对象:

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.IdAlbumArtist.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 语句中,我只是检查该属性是否在我的引用类型的命名空间下,如果是,我应该获取所有嵌套的属性值,但这是引发异常的地方。

最佳答案

这会失败,因为您正在尝试获取 Artist PropertyInfo 上的属性(property)实例:

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());

完整(稍作改动以避免在不需要时调用 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

关于c# - 在嵌套属性中使用 GetValue() 在反射中抛出 TargetException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12496791/

相关文章:

c# - 在 Rally .Net API : How to use Query. 运算符中。包含数组或列表(或条件)

c# - 如何使用反射调用泛型方法?

android - 如何使用泛型或反射来显示/隐藏 fragment ? Kotlin 安卓

c# - 在 C# 中序列化数组列表

c# - 在 C# 中使用线程用随机数填充数组

c# - 表值参数插入性能不佳

c# - 哈希集内存开销

.NET Code128 和 PDF417 条码库

c# - 正则表达式匹配整行文本,不包括 crlf

java - 是否有一种通用的 Java 方法来修剪对象图中的每个字符串?