泛型摘录

来源:互联网 发布:个人怎么查同盾数据 编辑:程序博客网 时间:2024/05/11 16:23

一段类型转化

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

 ///


            /// Gets the value.
            ///

            ///
            /// Name of the column.
            ///
            public T GetValue(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);
            }

原创粉丝点击