使用反射和getCount(.net 4)从对象获取集合

时间:2015-10-29 06:17:51

标签: c# system.reflection

我需要反思一个对象获取所有属性集合和

1)每个集合的GetCount

2)GetTotalCount(allCollectionCount)

3)使用此集合调用方法。

到目前为止,我已经完成了以简单的结构为基础的简单结构。     我陷入了如何调用此方法以及如何计算收集的问题。

有什么建议吗?

        using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text;

    namespace ConsoleApplication2
    {
        class Program
        {
            static void Main()
            {
                var request = GetDataRequest();

                //Get all properties 
                List<PropertyInfo> propInfoList =
                    new List<PropertyInfo>(request.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public));

                //Get collections only
                var myClassCollections=propInfoList.Where(xxx => xxx.PropertyType.GetInterfaces().Any(x => x == typeof (IEnumerable))).ToList();

                var totalCountForAllCollections=????
                foreach (var col in myClassCollections)
                {
                    //How do I call my Method DoSomething
                    //      DoSomething<?>(col.?????)   
                }

            }

            public void DoSomething<T>(List<T> objectCollection)
            {
                //etc...
            }
            private static DataRequest GetDataRequest()
            {
                DataRequest request = new DataRequest();
                request.Addresses.Add(new Address
                {
                    Id = 1,
                    City = "London",
                    Postcode = "32131",
                    Street = "London Road"
                });
                request.Addresses.Add(new Address
                {
                    Id = 2,
                    City = "NewYork",
                    Postcode = "3432",
                    Street = "NewYork Road"
                });

                request.Customers.Add(new Customer
                {
                    Id = 1,
                    Name = "Jo",
                    Surname = "Bloggs",
                });
                request.Customers.Add(new Customer
                {
                    Id = 1,
                    Name = "Jon",
                    Surname = "Bloggs2",
                });
                request.Customers.Add(new Customer
                {
                    Id = 1,
                    Name = "Jonny",
                    Surname = "Bloggs3",
                });
                return request;
            }
        }
        public class DataRequest
        {
            public DataRequest()
            {
                Customers = new List<Customer>();
                Orders = new List<Order>();
                Addresses = new List<Address>();

            }
            public List<Customer> Customers { get; set; }
            public List<Order> Orders { get; set; }
            public List<Address> Addresses { get; set; }

        }

        public class Customer
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Surname { get; set; }
        }

        public class Order
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string OrderNo { get; set; }
        }

        public class Address
        {
            public int Id { get; set; }
            public string Street { get; set; }
            public string City { get; set; }
            public string Postcode { get; set; }
        }
    }

1 个答案:

答案 0 :(得分:0)

快速又脏,你走了......

// ..
static class Program
{
    static void Main()
    {
        var request = GetDataRequest();

        //Get propertyValues for properties that are enumerable (i.e. lists,arrays etc)
        var collectionProperties = request.GetType()
                                          .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                                          .Where(propertInfo => propertInfo.PropertyType.GetInterfaces().Any(x => x == typeof(IEnumerable)))
                                          .Select(p => p.GetValue(request, null))
                                          .Cast<IEnumerable<object>>().ToList();

        var totalCountForAllCollections = 0;
        // iterate through the list of propertyValues
        foreach (var collectionPropertyValue in collectionProperties)
        {
            totalCountForAllCollections += collectionPropertyValue.Count();
            collectionPropertyValue.DoSomething();
        }

        System.Console.WriteLine("The total count for all collections is : {0}", totalCountForAllCollections);
        System.Console.WriteLine("press any key to exit");
        System.Console.ReadLine();
    }

    public static void DoSomething<T>(this IEnumerable<T> objectCollection)
    {
        //etc...
        // N.B. you will have to use typeof(T) to implement logic specific to the type
        // If the logic in this method is non-specific to the typeof(T) then Implement logic accordingly
        System.Console.WriteLine("The type of the collection is: {0}", objectCollection.GetType());
        System.Console.WriteLine("The count of items in this collection is:{0}", objectCollection.Count());
    }
    // ..
}
// ..