净解析与转换 [英] .Net Parse versus Convert
问题描述
在.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.
这篇关于净解析与转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!