LMS.service/LMS.Tools/Extensions/ConvertExtension.cs
2024-10-13 17:04:47 +08:00

45 lines
1.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}
}
}