净解析与转换

2023-09-03 00:23:59 作者:猪精男孩

在.net中,您可以读取一个字符串值,将使用两种.parse或Convert.To另一种数据类型。

In .Net you can read a string value into another data type using either .parse or Convert.To.

我不熟悉的语法分析与基本面的转换,所以我一直在亏损的时候问哪一个是好/更快/更合适。

I'm not familiar with the fundamentals of parse versus convert so I am always at a loss when asked which one is better/faster/more appropriate.

所以 - ?哪种方式最好是在什么样的情况下

So - which way is best in what type of circumstances?

推荐答案

Convert.ToXXX()方法是,可能是正确的或相似类型的对象,而 .Parse() .TryParse()是专门为字符串:

The Convert.ToXXX() methods are for objects that might be of the correct or similar type, while .Parse() and .TryParse() are specifically for strings:

//o is actually a boxed int
object o = 12345;

//unboxes it
int castVal = (int) 12345;

//o is a boxed enum
object o = MyEnum.ValueA;

//this will get the underlying int of ValueA
int convVal = Convert.ToInt32( o );

//now we have a string
string s = "12345";

//this will throw an exception if s can't be parsed
int parseVal = int.Parse( s );

//alternatively:
int tryVal;
if( int.TryParse( s, out tryVal ) ) {
    //do something with tryVal 
}

如果您编译与优化标志的TryParse非常快 - 这是得到一个数字字符串的最佳方式。但是,如果你有一个对象可能是一个int或可能是一个字符串Convert.ToInt32更快。

If you compile with optimisation flags TryParse is very quick - it's the best way to get a number from a string. However if you have an object that might be an int or might be a string Convert.ToInt32 is quicker.

相关推荐
 
精彩推荐
图片推荐