C#通用类型转换 Convert.ChangeType
static public object ChangeType(object value, Type type) { if (value == null && type.IsGenericType) return Activator.CreateInstance(type); if (value == null) return null; if (type == value.GetType()) return value; if (type.IsEnum) { if (value is string) return Enum.Parse(type, value as string); else return Enum.ToObject(type, value); } if (!type.IsInterface && type.IsGenericType) { Type innerType = type.GetGenericArguments()[0]; object innerValue = ChangeType(value, innerType); return Activator.CreateInstance(type, new object[] { innerValue }); } if (value is string && type == typeof(Guid)) return new Guid(value as string); if (value is string && type == typeof(Version)) return new Version(value as string); if (!(value is IConvertible)) return value; return Convert.ChangeType(value, type); }
今天在使用PetaPoco处理Nullable的时候出现了一个类型转化的问题,虽然最后发现是数据库类型错误,但在搜索过程中找到了这个通用的类型转换方法,觉得不错,留下来,也希望对更多的朋友提供帮助!
原文链接:http://www.cnblogs.com/genson/archive/2008/10/08/1306099.html
本文作者:拓荒者IT
本文链接:https://www.cnblogs.com/youring2/archive/2012/07/26/2610035.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
📌做了个微信公众号【拓荒者IT】,分享各种技术干货,新内容首发到公众号,欢迎关注❤️
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2011-07-26 Razor代码复用