设为首页 加入收藏

TOP

C#把对象类型转化为指定类型,转化失败时返回该类型默认值
2014-11-23 21:26:32 来源: 作者: 【 】 浏览:12
Tags:对象 类型 化为 指定 转化 失败 返回 默认

C#把对象类型转化为指定类型,转化失败时返回该类型默认值


///


///通用类型扩展方法类
///

public static class ObjectExtensions
{
///
///把对象类型转化为指定类型,转化失败时返回该类型默认值
///

/// 动态类型
/// 要转化的源对象
/// 转化后的指定类型的对象,转化失败返回类型的默认值
public static T CastTo(this object value)
{
object result;
Type type = typeof(T);
try
{
if (type.IsEnum)
{
result = Enum.Parse(type, value.ToString());
}
else if (type == typeof(Guid))
{
result = Guid.Parse(value.ToString());
}
else
{
result = Convert.ChangeType(value, type);
}
}
catch
{
result = default(T);
}


return (T)result;
}


///


/// 把对象类型转化为指定类型,转化失败时返回指定的默认值
///

/// 动态类型
/// 要转化的源对象
/// 转化失败返回的指定默认值
/// 转化后的指定类型对象,转化失败时返回指定的默认值
public static T CastTo(this object value, T defaultValue)
{
object result;
Type type = typeof(T);
try
{
result = type.IsEnum Enum.Parse(type, value.ToString()) : Convert.ChangeType(value, type);
}
catch
{
result = defaultValue;
}
return (T)result;
}
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇SparkSQL使用之Spark SQL CLI 下一篇C#对象转JSON字符串和JSON字符串..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: