相关疑难解决方法(0)

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

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

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; }
}
Run Code Online (Sandbox Code Playgroud)

从对象获取属性时,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()) …
Run Code Online (Sandbox Code Playgroud)

.net c# reflection

3
推荐指数
1
解决办法
7885
查看次数

标签 统计

.net ×1

c# ×1

reflection ×1