Accessing a Collection Through Reflection

前端 未结 9 2138
时光说笑
时光说笑 2020-12-14 00:39

Is there a way to iterate (through foreach preferably) over a collection using reflection? I\'m iterating over the properties in an object using reflection, and when the pr

9条回答
  •  一整个雨季
    2020-12-14 01:17

    Just for information may be it will be of someone's help... I had a class with nested classes and collection of some other classes. I wanted to save the property values of the class as well nested classes and collection of classes. My code is as follows:

     public void LogObject(object obj, int indent)
        {
            if (obj == null) return;
            string indentString = new string(' ', indent);
            Type objType = obj.GetType();
            PropertyInfo[] properties = objType.GetProperties();
    
            foreach (PropertyInfo property in properties)
            {
                Type tColl = typeof(ICollection<>);
                Type t = property.PropertyType;
                string name = property.Name;
    
    
                object propValue = property.GetValue(obj, null); 
                //check for nested classes as properties
                if (property.PropertyType.Assembly == objType.Assembly)
                {
                    string _result = string.Format("{0}{1}:", indentString, property.Name);
                    log.Info(_result);
                    LogObject(propValue, indent + 2);
                }
                else
                {
                    string _result = string.Format("{0}{1}: {2}", indentString, property.Name, propValue);
                    log.Info(_result);
                }
    
                //check for collection
                if (t.IsGenericType && tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) ||
                    t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl))
                {
                    //var get = property.GetGetMethod();
                    IEnumerable listObject = (IEnumerable)property.GetValue(obj, null);
                    if (listObject != null)
                    {
                        foreach (object o in listObject)
                        {
                            LogObject(o, indent + 2);
                        }
                    }
                }
            }
        }
    

    An called this function

    LogObject(obj, 0);
    

    However, I have some structs inside my classes and I need to figure out how to get their values. Moreoevr, I have some LIst. I need to get their value as well.... I will post if I update my code.

提交回复
热议问题