类型转换 ToCast
作者 : 管理员 发布于 2023-04-25 23:06:05 浏览 573 次
数据类型相互转换如:字符串转整型,字符串转日期

数据类型相互转换如:
字符串转整型,字符串转日期

首先要引用 XiaoFeng命名空间

下边三个扩展方法 就是类型转换的方法
最常用的就是 ToCast方法

/// <summary>
/// 类型相互转换
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="_">原对象</param>
/// <param name="defaultValue">默认值</param>
/// <returns></returns>
public static T ToCast<T>(this object _, T defaultValue = default(T))

/// <summary>
/// 类型相互转换
/// </summary>
/// <param name="o">对象</param>
/// <param name="type">类型</param>
/// <returns></returns>
public static object GetValue(this object o, Type type)

/// <summary>
/// 类型相互转换
/// </summary>
/// <param name="o">对象</param>
/// <param name="targetType">类型</param>
/// <param name="isGeneric">是否是泛类型</param>
/// <returns></returns>
public static object GetValue(this object o, Type targetType, out bool isGeneric)

用法示例:

using XiaoFeng;

int a = "10".ToCast<int>();
Int64 b = "10".ToCast<Int64>();
double c = "10".ToCast<double>();
DateTime d = "2022-01-19".ToCast<DateTime>();
float e = "".ToCast<float>(1.0);
int f = (int)"".GetValue(typeof(int));
Guid g = "58AFBEB5791311ECBF49FA163E542B11".ToCast<Guid>();
Guid h = "58AFBEB5-7913-11EC-BF49-FA163E542B11".ToCast<Guid>();

还有一系列专一处理字符串转相关类型的方法,如:

Int16 a = "1".ToInt16();
int b = "2".ToInt32();
Int64 c = "3".ToInt64();
UInt16 d = "4".ToUInt16();
UInt32 e = "5".ToUInt32();
UInt64 f ="6".ToUInt64();
float e = "7.2".ToFloat();
DateTime g = "2022-01-19 12:32".ToDateTime();
double h = "6.3".ToDouble();
byte i = "2".ToByte();
Boolean j = "1".ToBoolean();
Boolean k = "true".ToBoolean();
Boolean l = "False".ToBoolean();
Decimal m = "3.658".ToDecimal();
long n = "2584512".ToLong();
Guid o = "58AFBEB5791311ECBF49FA163E542B11".ToGuid();
Guid p = "58AFBEB5-7913-11EC-BF49-FA163E542B11".ToGuid();
所有评论(0)