据我所知,在.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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!