C#,从对象获取所有集合属性

Eat*_*oku 4 c# reflection collections

我有一个包含3个List集合的类,如下所示.

我试图有一个逻辑,它将遍历对象的"集合"属性,并使用存储在这些集合中的数据执行一些操作.

我只是想知道是否有一种简单的方法来使用foreach.谢谢

public class SampleChartData
    {
        public List<Point> Series1 { get; set; }
        public List<Point> Series2 { get; set; }
        public List<Point> Series3 { get; set; }

        public SampleChartData()
        {
            Series1 = new List<Point>();
            Series2 = new List<Point>();
            Series3 = new List<Point>();
        }
    }
Run Code Online (Sandbox Code Playgroud)

max*_*max 12

从对象获取所有IEnumerable <T>的函数:

public static IEnumerable<IEnumerable<T>> GetCollections<T>(object obj)
{
    if(obj == null) throw new ArgumentNullException("obj");
    var type = obj.GetType();
    var res = new List<IEnumerable<T>>();
    foreach(var prop in type.GetProperties())
    {
        // is IEnumerable<T>?
        if(typeof(IEnumerable<T>).IsAssignableFrom(prop.PropertyType))
        {
            var get = prop.GetGetMethod();
            if(!get.IsStatic && get.GetParameters().Length == 0) // skip indexed & static
            {
                var collection = (IEnumerable<T>)get.Invoke(obj, null);
                if(collection != null) res.Add(collection);
            }
        }
    }
    return res;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用类似的东西

var data = new SampleChartData();
foreach(var collection in GetCollections<Point>(data))
{
    foreach(var point in collection)
    {
        // do work
    }
}
Run Code Online (Sandbox Code Playgroud)

迭代所有元素.


Gre*_*g B 2

使用反射来获取对象属性。然后迭代那些要查看的内容is IEnumerable<T>。然后迭代 IEnumerable 属性

  • 需要注意的是,字符串也显示为 IEnumerable (6认同)