TypeConverter vs.Convert vs.TargetType.Parse [英] TypeConverter vs. Convert vs. TargetType.Parse

查看:73
本文介绍了TypeConverter vs.Convert vs.TargetType.Parse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 方法:

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)?

推荐答案

根据我的个人喜好和编码标准,我选择以下各项:

According to my personal preference and coding standards I choose between the following:


  1. 转换。当我绝对确定值将是我期望的值时,将使用此值。

  1. Convert. I use this when I am absolutely sure that the values will be what I expect.

int i = Convert.ToInt32("123");


  • TryParse 。我在处理用户输入时使用它。这还具有在解析时能够使用本地化格式的好处。

  • TryParse. I use this when I am handling user input. This also has the benefit to be able to use localized formatting when parsing.

    int i = 0;
    bool parsed = Int32.TryParse("123", out i);
    


  • 也可以使用TryParseExact,可以解析某种模式的地方。在某些情况下可能会有用。

    There is also the possibility to use TryParseExact, where a certain pattern can be parsed. It can be useful in certain cases.

    这篇关于TypeConverter vs.Convert vs.TargetType.Parse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆