TypeConverter vs. Convert vs. TargetType.Parse

编程入门 行业动态 更新时间:2024-10-26 16:31:52
本文介绍了TypeConverter vs. Convert vs. TargetType.Parse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

据我所知,在.NET中转换数据类型至少有3种方式:

As far as I know, there are at least 3 ways to convert data types in .NET:

使用 System.ComponentModel.TypeConverter

var conv = System.ComponentModel.TypeDescriptor.GetConverter(typeof(int)); var i1 = (int)conv.ConvertFrom("123");

使用 System.Convert.ChangeType():

var i2 = (int) Convert.ChangeType("123", typeof (int));

使用目标类型的 Parse/TryParse 方法:

using the Parse/TryParse methods of the destination type:

var i3 = int.Parse("123"); // or TryParse

是否有任何指南或经验法则何时使用哪种方法在 .NET 基本数据类型之间进行转换(尤其是从字符串到其他数据类型)?

Are there any guidelines or rules-of-thumb when to use which method to convert between the .NET base data types (especially from string to some other data type)?

推荐答案

我要晚 6 年在这里发帖,因为我认为这是一个很好的问题,我对现有的答案并不满意.

I'm going to post here 6 years late, because I think this is a good question and I am not satisfied with the existing answers.

静态 Parse/TryParse 方法只能在当您想要从字符串转换为具有这些方法的类型 时使用.(如果您预计转换可能会失败,请使用 TryParse).

The static Parse/TryParse methods can be used only when you want to convert from string to the type that has those methods. (use TryParse when you expect that the conversion may fail).

System.Convert 的意义在于,它的 文档 说,将从一种基本数据类型转换为另一种基本数据类型.请注意,使用 Convert 时,您还可以使用获取 Object 并自行确定如何转换它的方法.

The point of System.Convert is, as its documentation says, to convert from a base data type to another base data type. Note that with Convert you also have methods that take an Object and figure out by themselves how to convert it.

至于System.ComponentModel.TypeConverter,作为typeconverter"堆栈溢出标签的文档,当您想要提供类实例的文本表示以供设计器序列化 或用于在属性网格中显示

As to System.ComponentModel.TypeConverter, as the "typeconverter" stack overflow tag's documentation, they are used primarily to convert to and from string, when you want to provide a text representation of a class instance for use by designer serialization or for display in property grids

更多推荐

TypeConverter vs. Convert vs. TargetType.Parse

本文发布于:2023-11-07 06:50:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565811.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Convert   TypeConverter   Parse   TargetType

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!