80 lines
1.2 KiB
C#
80 lines
1.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Work.Extension;
|
|
|
|
public static class ConvertExtension
|
|
{
|
|
#region 转换为string
|
|
/// <summary>
|
|
/// 将object转换为string,若转换失败,则返回string.Empty。不抛出异常。
|
|
/// </summary>
|
|
/// <param name="obj"></param>
|
|
/// <returns></returns>
|
|
public static string ParseToStr(this object obj)
|
|
{
|
|
try
|
|
{
|
|
if (obj == null)
|
|
{
|
|
return string.Empty;
|
|
}
|
|
else
|
|
{
|
|
if (obj is DateTime dt)
|
|
return dt.ToString("yyyy-MM-dd HH:mm:ss");
|
|
return obj.ToString();
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return string.Empty;
|
|
}
|
|
}
|
|
|
|
public static string ParseToNullableStr(this object obj)
|
|
{
|
|
try
|
|
{
|
|
if (obj == null)
|
|
{
|
|
return null;
|
|
}
|
|
else
|
|
{
|
|
if (obj is DateTime dt)
|
|
return dt.ToString("yyyy-MM-dd HH:mm:ss");
|
|
return obj.ToString();
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public static string ParseToStrs<T>(this object obj, string split = ",")
|
|
{
|
|
try
|
|
{
|
|
var list = obj as IEnumerable<T>;
|
|
if (list != null)
|
|
{
|
|
return string.Join(split, list);
|
|
}
|
|
else
|
|
{
|
|
return obj.ToString();
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
return string.Empty;
|
|
}
|
|
}
|
|
#endregion
|
|
}
|