泛型摘录

一段类型转化

--------------------------------------------------------------------

 /// <summary>
            /// Gets the value.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="columnName">Name of the column.</param>
            /// <returns></returns>
            public T GetValue<T>(string columnName)
            {
                columnName = columnName.ToLowerInvariant();
                object oVal;

                try
                {
                    oVal = this[columnName].CurrentValue;
                }
                catch
                {
                    throw new ArgumentException("There's no column called '" + columnName + "' for this object", "columnName");
                }

                if(oVal == null || oVal == DBNull.Value)
                    return default(T);

                Type type = typeof(T);

                if(type == typeof(object))
                    return (T)oVal;

                // handle nullable type conversion
                if(IsNullable(type))
                {
                    NullableConverter converter = new NullableConverter(type);
                    type = converter.UnderlyingType;
                }

                //if (IsNullable(type) || type == typeof(object))
                //{
                //    if (type == typeof(bool?))
                //        return (T)(object)Convert.ToBoolean(oVal);
                //    return (T)oVal;
                //}

                //if (type == typeof(Guid))
                //    return (T)(object)new Guid(oVal.ToString());

                Type valType = oVal.GetType();
                if(valType == typeof(Byte[]))
                    return (T)Convert.ChangeType(oVal, valType);

                return (T)Convert.ChangeType(oVal, type);
            }

你可能感兴趣的:(泛型)