45 lines
1.1 KiB
C#
45 lines
1.1 KiB
C#
|
|
namespace LMS.Tools.Extensions
|
|||
|
|
{
|
|||
|
|
public class ConvertExtension
|
|||
|
|
{
|
|||
|
|
/// <summary>
|
|||
|
|
/// 将字符串转换为long,默认或者是转换错误返回0
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="str"></param>
|
|||
|
|
/// <returns></returns>
|
|||
|
|
public static long ObjectToLong(object obj)
|
|||
|
|
{
|
|||
|
|
if (obj == null)
|
|||
|
|
return 0;
|
|||
|
|
|
|||
|
|
if (obj is long longValue)
|
|||
|
|
return longValue;
|
|||
|
|
|
|||
|
|
if (obj is int intValue)
|
|||
|
|
return intValue;
|
|||
|
|
|
|||
|
|
if (obj is string strValue)
|
|||
|
|
{
|
|||
|
|
if (long.TryParse(strValue, out long result))
|
|||
|
|
return result;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 处理其他数值类型
|
|||
|
|
if (obj is IConvertible convertible)
|
|||
|
|
{
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
return convertible.ToInt64(System.Globalization.CultureInfo.InvariantCulture);
|
|||
|
|
}
|
|||
|
|
catch
|
|||
|
|
{
|
|||
|
|
// 转换失败,返回0
|
|||
|
|
return 0;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return 0; // 默认返回0
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|