Пример #1
0
 /// <summary>
 /// Set the property value using the string value.
 /// </summary>
 /// <param name="obj">Object whose property will be set.</param>
 /// <param name="prop">Property information.</param>
 /// <param name="propVal">Property value to set.</param>
 public static void SetProperty(object obj, PropertyInfo prop, string propVal)
 {
     // Correct property with write access
     if (prop != null && prop.CanWrite)
     {
         // Check same Type
         if (ReflectionTypeChecker.CanConvertToCorrectType(prop, propVal))
         {
             object convertedVal = ReflectionTypeChecker.ConvertToSameType(prop, propVal);
             prop.SetValue(obj, convertedVal, null);
         }
     }
 }
Пример #2
0
        /// <summary>
        /// Set the object properties using the prop name and value.
        /// </summary>
        /// <typeparam name="T">A class type.</typeparam>
        /// <param name="obj">Object whose property will be set.</param>
        /// <param name="propName">Property name to set.</param>
        /// <param name="propVal">Property value to set.</param>
        public static void SetProperty <T>(object obj, string propName, object propVal) where T : class
        {
            // Remove spaces.
            propName = propName.Trim();
            if (string.IsNullOrEmpty(propName))
            {
                throw new ArgumentException("Property name is empty.");
            }

            Type         type         = obj.GetType();
            PropertyInfo propertyInfo = type.GetProperty(propName);

            // Correct property with write access
            if (propertyInfo != null && propertyInfo.CanWrite)
            {
                // Check same Type
                if (ReflectionTypeChecker.CanConvertToCorrectType(propertyInfo, propVal))
                {
                    object convertedVal = ReflectionTypeChecker.ConvertToSameType(propertyInfo, propVal);
                    propertyInfo.SetValue(obj, convertedVal, null);
                }
            }
        }