145 lines
3.6 KiB
Plaintext
Executable File
145 lines
3.6 KiB
Plaintext
Executable File
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using System.Text;
|
||
|
||
namespace GXWebApi.Common
|
||
{
|
||
|
||
/// <summary>
|
||
/// 扩展方法类
|
||
/// </summary>
|
||
public static class Extensions
|
||
{
|
||
/// <summary>
|
||
/// 安全转换为字符串(处理null和DBNull)
|
||
/// </summary>
|
||
public static string ToStringEx(this object obj)
|
||
{
|
||
if (obj == null || obj == DBNull.Value)
|
||
return string.Empty;
|
||
return obj.ToString();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 安全转换为整数(处理null和DBNull)
|
||
/// </summary>
|
||
public static int ToInt(this object obj)
|
||
{
|
||
if (obj == null || obj == DBNull.Value)
|
||
return 0;
|
||
|
||
int result;
|
||
if (int.TryParse(obj.ToString(), out result))
|
||
return result;
|
||
return 0;
|
||
}
|
||
|
||
public static int ToInt32(this object pf)
|
||
{
|
||
if (Convert.IsDBNull(pf) || pf == null)
|
||
{
|
||
return 0;
|
||
}
|
||
|
||
if (pf.ToString() == "")
|
||
{
|
||
return 0;
|
||
}
|
||
|
||
try
|
||
{
|
||
if (pf is bool)
|
||
{
|
||
if ((bool)pf)
|
||
{
|
||
return 1;
|
||
}
|
||
|
||
return 0;
|
||
}
|
||
|
||
return (int)Convert.ToDecimal(pf);
|
||
}
|
||
catch
|
||
{
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 安全转换为可为空的DateTime(处理null和DBNull)
|
||
/// </summary>
|
||
public static DateTime? ToDateTimeNullable(this object obj)
|
||
{
|
||
if (obj == null || obj == DBNull.Value)
|
||
return null;
|
||
|
||
DateTime result;
|
||
if (DateTime.TryParse(obj.ToString(), out result))
|
||
return result;
|
||
return null;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 判断字符串是否为空或空白
|
||
/// </summary>
|
||
public static bool IsNullOrEmpty(this object pf)
|
||
{
|
||
if (Convert.IsDBNull(pf) || pf == null)
|
||
{
|
||
return true;
|
||
}
|
||
|
||
Type type = pf.GetType();
|
||
if (type == typeof(string))
|
||
{
|
||
return pf.ToStringEx().Trim() == "";
|
||
}
|
||
|
||
if (type == typeof(int) || type == typeof(short) || type == typeof(int) || type == typeof(long))
|
||
{
|
||
return pf.ToInt() == 0;
|
||
}
|
||
|
||
if (type == typeof(decimal) || type == typeof(double) || type == typeof(float))
|
||
{
|
||
return pf.ToDecimal() == 0m;
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
|
||
public static decimal ToDecimal(this object pf)
|
||
{
|
||
if (Convert.IsDBNull(pf) || pf == null)
|
||
{
|
||
return 0m;
|
||
}
|
||
|
||
if (pf.ToString() == "")
|
||
{
|
||
return 0m;
|
||
}
|
||
|
||
try
|
||
{
|
||
return Convert.ToDecimal(pf);
|
||
}
|
||
catch
|
||
{
|
||
return 0m;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 判断字符串是否为空、空白或仅包含空格
|
||
/// </summary>
|
||
public static bool IsNullOrWhiteSpace(this string str)
|
||
{
|
||
return string.IsNullOrWhiteSpace(str);
|
||
}
|
||
}
|
||
} |