解析诉 TryParse
Parse() 和 TryParse() 有什么区别?
What is the difference between Parse() and TryParse()?
int number = int.Parse(textBoxNumber.Text);
// The Try-Parse Method
int.TryParse(textBoxNumber.Text, out number);
是否有某种形式的错误检查,例如 Try-Catch 块?
Is there some form of error-checking like a Try-Catch Block?
Parse
如果无法解析值则抛出异常,而 TryParse
返回一个 bool
表示是否成功.
Parse
throws an exception if it cannot parse the value, whereas TryParse
returns a bool
indicating whether it succeeded.
TryParse
不仅仅是在内部 try
/catch
- 它的全部意义在于它无例外地实现,因此它很快.事实上,它最有可能实现的方式是,Parse
方法在内部调用 TryParse
,然后在返回 false
时抛出异常.
TryParse
does not just try
/catch
internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the Parse
method will call TryParse
and then throw an exception if it returns false
.
简而言之,如果您确定该值有效,请使用 Parse
;否则使用 TryParse
.
In a nutshell, use Parse
if you are sure the value will be valid; otherwise use TryParse
.