访问嵌套对象字段

问题描述 投票:0回答:1

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

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)?

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

谢谢您的帮助!

最大

c# system.reflection
1个回答
0
投票

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

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 };
}

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

© www.soinside.com 2019 - 2024. All rights reserved.