Convert.ChangeType() 对于字符串值有意义吗?
我发现 @hugoware 关于解析值的精彩帖子:http://hugoware.net/blog/more-control-when-parsing-values。我在项目中重复使用了他的代码示例,但现在我注意到在最后一个块(代码的第 154 行)中,他使用 Convert.ChangeType() 方法作为“转换”值的最后一次尝试。
现在我想知道这是否有意义,因为我们总是从字符串值开始,并且我猜 Convert.ChangeType 只对值类型进行转换?尝试这样做是否有意义,还是总是会失败?
I found this great post by @hugoware about parsing values: http://hugoware.net/blog/more-control-when-parsing-values. I re-used his code sample in a project but now I noticed in the last block (line 154 of his code) he uses the Convert.ChangeType() method as a last attempt to "convert" the value.
Now I wonder if this makes sense, since we're always starting from a string value and I guess Convert.ChangeType only does casting on value types? Does it make sense to try that or will it always fail?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只想转换字符串,我建议您使用 ConvertToString / ConvertFromString
--
If you just want to convert strings, I advice you to use ConvertToString / ConvertFromString
--
您可以将 Convert.ChangeType() 与字符串一起使用。请参阅 MSDN 文档: ChangeType
来自 MSDN:
在上述情况下,从字符串有意义。
通过使用这种方法,我认为可以进一步扩展它以处理非字符串值,例如,
能够从任何值进行转换可能是有意义的,例如,如果您有一个提供第三方 dll 的接口对象的数字表示(它已经发生了!)您可以使用更通用的代码版本在第 3 方表示和对您的代码更有意义的另一种表示之间进行转换。
you can use Convert.ChangeType() with strings. See the MSDN documentation: ChangeType
From MSDN:
In the above case converting from a string makes sense.
By using this method I suppose it is possible to extend it even further to cope with non-string values e.g.
It might make sense to be able to convert from any value around for example, if you had an interface to a 3rd party dll that provided a numerical representation of an object (it has happened!) you could use the more generic version of the code to convert between the 3rd party representation and another representation that makes more sense to your code.