protected LibraryResource StringsSetter(LibraryResource libResource, XElement item) { foreach (PropertyInfo property in libResource.GetType().GetProperties().Where(pi => pi.PropertyType == typeof(string))) { var value = item.Attribute(property.Name); if (Attribute.IsDefined(property, typeof(RequiredAttribute), true)) { if (string.IsNullOrEmpty(value.ToString())) { throw new Exception("this is mandatory field"); } } // а если не равен null - можно будет безопасно возпользоваться // свойством Value, объекта value. if (value != null) { property.SetValue(libResource, value.Value); } } return(libResource); }
protected LibraryResource DateSetter(LibraryResource libResource, XElement item) { foreach (PropertyInfo property in libResource.GetType().GetProperties().Where(pi => pi.PropertyType == typeof(Nullable <DateTime>))) { DateTime?value = null; try { value = XmlConvert.ToDateTime(item.Attribute(property.Name).Value, XmlDateTimeSerializationMode.Local); } catch { value = null; } if (Attribute.IsDefined(property, typeof(RequiredAttribute), true)) { if (!value.HasValue) { throw new Exception("this is mandatory field"); } } property.SetValue(libResource, value); } return(libResource); }