예제 #1
0
        /// <summary>
        /// Set the object properties using the prop name and value
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        public static void SetProperty <T>(T obj, string propName, string propVal) where T : class
        {
            Guard.IsNotNull(obj, "Object containing properties to set is null");
            Guard.IsTrue(!string.IsNullOrEmpty(propName), "Property name not supplied.");

            // Remove spaces.
            propName = propName.Trim();
            if (string.IsNullOrEmpty(propName))
            {
                throw new ArgumentException("Property name is empty.");
            }

            var type         = obj.GetType();
            var propertyInfo = type.GetProperty(propName);

            // Correct property with write access
            if (propertyInfo != null && propertyInfo.CanWrite)
            {
                // Check same Type
                if (ReflectionTypeChecker.CanConvertToCorrectType(propertyInfo, propVal))
                {
                    var convertedVal = ReflectionTypeChecker.ConvertToSameType(propertyInfo, propVal);
                    propertyInfo.SetValue(obj, convertedVal, null);
                }
            }
        }
예제 #2
0
        /// <summary>
        /// Set the property value using the string value.
        /// </summary>
        /// <param name="options"></param>
        /// <param name="prop"></param>
        /// <param name="configValue"></param>
        public static void SetProperty(object obj, PropertyInfo prop, string propVal)
        {
            Guard.IsNotNull(obj, "Object containing properties to set is null");
            Guard.IsNotNull(prop, "Property not supplied.");

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