2015-10-29 1 views
2

У меня есть требование, чтобы отразить на объекте получить все свойства, коллекции иПолучить Коллекции от объекта с помощью отражения и GetCount (.net 4)

1) GetCount для каждой коллекции

2) GetTotalCount (allCollectionCount)

3) Вызвать метод с этой коллекцией.

Ниже приведено то, что я сделал до сих пор с созданной кивкой структурой для semplicity. Я застрял в том, как назвать этот метод и как получить счетчик для сбора.

Любые предложения?

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

ответ

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()); 
    } 
    // .. 
} 
// .. 
+0

Спасибо за ваше время и усилия .I увидеть, что вы делаете, и, надеюсь, я не могу сделать это work.currently «collectionProperties» не компилировать значение «на выбранном бите» не может быть выведено так же для getvalue – developer9969

+0

@ developer9969, может быть, разница в том, что мой класс _Program_ ** статический **, а ваш нет? – AfzalHassen

+0

Спасибо за ваш ответ. я просто скопировал ваш код целиком, и я получаю «отсутствие перегрузки для метода getvalue принимает один аргумент». Извините за беспокойство, я буду работать с ним. Спасибо – developer9969