c# – 将字符串转换为类型实例
发布时间:2020-12-16 00:19:16 所属栏目:百科 来源:网络整理
导读:你有这些代码的替代品,我想要一个更通用的代码 我尝试过转换类,但没有成功 public object convert(Type type,string value) { object r = null; if (type == typeof(bool)) { r = bool.Parse(value); } else if (type == typeof(int)) { r = int.Parse(value
你有这些代码的替代品,我想要一个更通用的代码
我尝试过转换类,但没有成功 public object convert(Type type,string value) { object r = null; if (type == typeof(bool)) { r = bool.Parse(value); } else if (type == typeof(int)) { r = int.Parse(value); } else if (type == typeof(string)) { r = value; } return r; } 解决方法var conv = TypeDescriptor.GetConverter(type); return conv.ConvertFromInvariantString(value); 如果您不想要“不变”,则存在其他转换操作.这取决于您的需求.如果您想要应用语言环境,请参阅ConvertFromString等. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |