访问嵌套对象字段

时间:2020-06-16 13:24:39

标签: c# system.reflection

我想访问一个嵌套在结构中的对象的字段名称,如下所示:

public class Playerframe
{
  public string Attr1;
  public string Attr2;
}

public class MatchMoment
{
  public int MomentNr;
  public Dictionary <int, Playerframe> PlayerData;
}

public DataTable CreateTable (List<dynamic>Moments)
{
 DataTable table = new DataTable();
 List<string> = Moments[0]...... 

 /// get all class Properties, including the Playerframe properties in order 
 /// to create correctly named DataTable columns
 /// The List<string> should finally contain {"MomentNr","Attr1","Attr2"}

 return table;
}

我现在的问题是如何使用System.Reflection访问MatchMoment对象对象中存储在Dictionary值中的字段名称(例如Attr1)?

我想编写一个函数,该函数根据方法参数中定义的任何给定对象的属性创建一个数据表对象,如上所述。

谢谢您的帮助!

最大

1 个答案:

答案 0 :(得分:1)

我认为以下片段可能会为您提供所需的内容。基本上,它会遍历列表的元素类型的属性以获取其名称,如果是通用属性类型,则以递归方式获取通用类型参数的属性的名称。

public DataTable CreateTable(List<dynamic> Moments)
{
    var table = new DataTable();

    var elementType = GetElementType(Moments);
    var propertyNames = GetPropertyNames(elementType);

    // Do something with the property names . . .

    return table;
}

private static Type GetElementType(IEnumerable<dynamic> list) =>
    list.GetType().GetGenericArguments()[0];

private static IEnumerable<string> GetPropertyNames(Type t)
{
    return t.GetProperties().SelectMany(getPropertyNamesRecursively);

    IEnumerable<string> getPropertyNamesRecursively(PropertyInfo p) =>
        p.PropertyType.IsGenericType
            ? p.PropertyType.GetGenericArguments().SelectMany(GetPropertyNames)
            : new[] { p.Name };
}

请注意,这仅查看属性,而您当前的类仅使用字段。但是,使用属性被认为是公共访问数据的最佳实践,因此将您的字段更改为属性可能是值得的。如果您确实想将它们保留为字段,则可能需要进行一些调整,但是递归展开通用类型的想法仍然相同。

相关问题