MSDN.WhiteKnight - Stack Overflow answers
Ответ на "Очистка объекта типа IEnumerable полученный через PropertyInfo"
Answer 926484
Если под "Очистить" понимается "Вызвать метод Clear() через позднее связывание или упасть, если его нету", то как-то так:
Type RuntimeType = obj.GetType(); MethodInfo method = RuntimeType.GetMethod("Clear"); if (method == null) throw new ApplicationException("Object type does not have Clear() method!"); else method.Invoke(obj, new object[] { });
Если под "Очистить" понимается "Присвоить свойству значение новой пустой коллекции", то как-то так:
static bool IsIEnumerable(Type t) { if (!t.IsGenericType) return false; Type InterfType = typeof(IEnumerable<>); if (t.GetGenericTypeDefinition() == InterfType) return true; foreach (Type it in t.GetInterfaces()) { if (it.IsGenericType && it.GetGenericTypeDefinition() == InterfType) return true; } return false; } static void ClearIEnumerable(PropertyInfo prop, object obj) { Type PropType = prop.PropertyType; if (!IsIEnumerable(PropType)) throw new ArgumentException("Property is not IEnumerable<T>"); Type InnerType = PropType.GetGenericArguments()[0]; Type ListType; if (PropType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) ListType = typeof(List<>).MakeGenericType(InnerType); else ListType = PropType; object new_val = Activator.CreateInstance(ListType); prop.SetValue(obj, new_val); }
Content is retrieved from StackExchange API.
Auto-generated by ruso-archive tools.