public static class DataFormatHelper
{
public static int ToInt(this object val, int defVal = default(int))
{
return val.To<int>(defVal);
}
/// <summary>
/// 通用类型转换
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val"></param>
/// <param name="defVal"></param>
/// <returns></returns>
public static T To<T>(this object val, T defVal = default(T))
{
if (val == null)
return (T)defVal;
if (val is T)
return (T)val;
if (val is DBNull)
return (T)defVal;
Type type = typeof(T);
try
{
if (type.BaseType == typeof(Enum))
{
return (T)Enum.Parse(type, val.ToString(), true);
}
else
{
return (T)Convert.ChangeType(val, type);
}
}
catch
{
return defVal;
}
}
}
C# 数据类型转换工具类
猜你喜欢
转载自blog.csdn.net/Helloantoherday/article/details/125748920
今日推荐
周排行