示例#1
0
 /// <summary>
 ///     Converts an Object to the specified target type or returns the default value if
 ///     those 2 types are not convertible.
 ///     <para>Any exceptions are optionally ignored (<paramref name="ignoreException"/>).</para>
 ///     <para>
 ///     If the exceptions are not ignored and the <paramref name="obj"/> can't be convert even if
 ///     the types are convertible with each other, an exception is thrown.</para>
 /// </summary>
 /// <typeparam name = "T"></typeparam>
 /// <param name = "obj">The value.</param>
 /// <param name = "defaultValue">The default value.</param>
 /// <param name = "ignoreException">if set to <c>true</c> ignore any exception.</param>
 /// <returns>The target type</returns>
 public static T ConvertTo <T>(this Object obj, T defaultValue, bool ignoreException)
 {
     if (ignoreException)
     {
         try
         {
             return(obj.ConvertTo <T>());
         }
         catch
         {
             return(defaultValue);
         }
     }
     return(obj.ConvertTo <T>());
 }
        /// <summary>
        /// 转换对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static T ConvertTo <T>(this Object model) where T : new()
        {
            if (model == null)
            {
                return(default(T));
            }
            var targetType = typeof(T);
            var sourceType = model.GetType();

            return((T)model.ConvertTo(targetType));
        }
示例#3
0
 /// <summary>
 ///     Converts an Object to the specified target type or returns the default value.
 ///     <para>Any exceptions are ignored. </para>
 /// </summary>
 /// <typeparam name = "T"></typeparam>
 /// <param name = "obj">The value.</param>
 /// <param name = "defaultValue">The default value.</param>
 /// <returns>The target type</returns>
 public static T ConvertToAndIgnoreException <T>(this Object obj, T defaultValue)
 {
     return(obj.ConvertTo(defaultValue, true));
 }
示例#4
0
 /// <summary>
 ///     Converts an Object to the specified target type or returns the default value if
 ///     those 2 types are not convertible.
 ///     <para>
 ///     If the <paramref name="obj"/> can't be convert even if the types are
 ///     convertible with each other, an exception is thrown.</para>
 /// </summary>
 /// <typeparam name = "T"></typeparam>
 /// <param name = "obj">The value.</param>
 /// <returns>The target type</returns>
 public static T ConvertTo <T>(this Object obj)
 {
     return(obj.ConvertTo(default(T)));
 }