Ejemplo n.º 1
0
        /// <summary>
        /// Returns the value of this setting casted to its desired type.
        /// </summary>
        /// <typeparam name="T">The type to cast the setting to. If this type is a type that implements <see cref="T:IStringSettingConvertible"/>,
        /// an automatic conversion as defined in that type will be performed.</typeparam>
        /// <returns>The value of this setting casted to its desired type. If the value is null then the default value for <typeparamref name="T"/> is returned.</returns>
        public T GetValue <T>()
        {
            if (Value == null)
            {
                return(default(T));
            }

            // If the value is a string
            if (Value is string && typeof(T).GetInterface(typeof(IStringSettingConvertible).Name) != null)
            {
                // Look for an empty constructor, even if it is private (only then we can instantiate this type)
                if (typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Any(ci => ci.GetParameters().Length == 0))
                {
                    IStringSettingConvertible convertible = (IStringSettingConvertible)Activator.CreateInstance(typeof(T), true);
                    convertible.Convert((string)Value);
                    return((T)convertible);
                }
            }

            return((T)Value);
        }
        /// <summary>
        /// Takes an <see cref="Object"/> which represents the setting value and tries to return its really value
        /// using a conversion to <see cref="IStringSettingConvertible"/>. If that failed then the value is returned as-is.
        /// </summary>
        /// <param name="type">The expected true type of the setting</param>
        /// <param name="value">The setting value.</param>
        /// <returns></returns>
        public static object ConvertFromSetting(Type type, object value)
        {
            if (value == null)
            {
                return(null);
            }

            // If the value is a string
            if (value is string && type.GetInterface(typeof(IStringSettingConvertible).Name) != null)
            {
                // Look for an empty constructor, even if it is private (only then we can instantiate this type)
                if (type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Any(ci => ci.GetParameters().Length == 0))
                {
                    IStringSettingConvertible convertible = (IStringSettingConvertible)Activator.CreateInstance(type, true);
                    convertible.Convert((string)value);
                    return(convertible);
                }
            }

            // Try the basic method at last.
            return(Convert.ChangeType(value, type));
        }