C# 解析诉 TryParse
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/467613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse v. TryParse
提问by Kredns
What is the difference between Parse() and TryParse()?
Parse() 和 TryParse() 有什么区别?
int number = int.Parse(textBoxNumber.Text);
// The Try-Parse Method
int.TryParse(textBoxNumber.Text, out number);
Is there some form of error-checking like a Try-Catch Block?
是否有某种形式的错误检查,如 Try-Catch 块?
采纳答案by Greg Beech
Parse
throws an exception if it cannot parse the value, whereas TryParse
returns a bool
indicating whether it succeeded.
Parse
如果无法解析该值,则抛出异常,而TryParse
返回一个bool
指示是否成功。
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
.
TryParse
不只是try
/catch
内部 - 它的全部意义在于它毫无例外地实现,因此它很快。事实上,它最有可能实现的方式是,该Parse
方法将在内部调用TryParse
,然后在返回时抛出异常false
。
In a nutshell, use Parse
if you are sure the value will be valid; otherwise use TryParse
.
简而言之,Parse
如果您确定该值有效,请使用;否则使用TryParse
.
回答by M4N
If the string can not be converted to an integer, then
如果字符串不能转换为整数,则
int.Parse()
will throw an exceptionint.TryParse()
will return false (but not throw an exception)
int.Parse()
会抛出异常int.TryParse()
将返回 false(但不会抛出异常)
回答by Ray Booysen
The TryParse method allows you to test whether something is parseable. If you try Parse as in the first instance with an invalid int, you'll get an exception while in the TryParse, it returns a boolean letting you know whether the parse succeeded or not.
TryParse 方法允许您测试某些内容是否可解析。如果您像在第一个实例中一样尝试 Parse 并使用无效的 int,您将在 TryParse 中得到一个异常,它返回一个布尔值,让您知道解析是否成功。
As a footnote, passing in null to most TryParse methods will throw an exception.
作为脚注,将 null 传递给大多数 TryParse 方法将引发异常。
回答by Mark Brittingham
TryParse does not return the value, it returns a status code to indicate whether the parse succeeded (and doesn't throw an exception).
TryParse 不返回值,它返回一个状态代码来指示解析是否成功(并且不抛出异常)。
回答by Gulzar Nazim
TryParse and the Exception Tax
Parse throws an exception if the conversion from a string to the specified datatype fails, whereas TryParse explicitly avoids throwing an exception.
如果从字符串到指定数据类型的转换失败,Parse 会抛出异常,而 TryParse 会明确避免抛出异常。
回答by eyaler
double.Parse("-"); raises an exception, while double.TryParse("-", out parsed); parses to 0 so I guess TryParse does more complex conversions.
double.Parse("-"); 引发异常,而 double.TryParse("-", out parsed); 解析为 0,所以我猜 TryParse 会进行更复杂的转换。
回答by magallanes
For the record, I am testing two codes: That simply try to convert from a string to a number and if it fail then assign number to zero.
作为记录,我正在测试两个代码:这只是尝试将字符串转换为数字,如果失败,则将数字分配为零。
if (!Int32.TryParse(txt,out tmpint)) {
tmpint = 0;
}
and:
和:
try {
tmpint = Convert.ToInt32(txt);
} catch (Exception) {
tmpint = 0;
}
For c#, the best option is to use tryparse because try&Catch alternative thrown the exception
对于 c#,最好的选择是使用 tryparse 因为 try&Catch 替代抛出异常
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll
That it is painful slow and undesirable, however, the code does not stop unless Debug's exception are settled for stop with it.
这是痛苦的缓慢和不可取的,但是,除非调试的异常被解决,否则代码不会停止。
回答by LifeOfPi
I know its a very old post but thought of sharing few more details on Parse vs TryParse.
我知道这是一篇很老的帖子,但我想分享更多关于 Parse 与 TryParse 的细节。
I had a scenario where DateTime needs to be converted to String and if datevalue null or string.empty we were facing an exception. In order to overcome this, we have replaced Parse with TryParse and will get default date.
我有一个场景,其中 DateTime 需要转换为 String 并且如果 datevalue null 或 string.empty 我们面临异常。为了克服这个问题,我们用 TryParse 替换了 Parse 并将获得默认日期。
Old Code:
旧代码:
dTest[i].StartDate = DateTime.Parse(StartDate).ToString("MM/dd/yyyy");
dTest[i].EndDate = DateTime.Parse(EndDate).ToString("MM/dd/yyyy");
New Code:
新代码:
DateTime startDate = default(DateTime);
DateTime endDate=default(DateTime);
DateTime.TryParse(dPolicyPaidHistories[i].StartDate, out startDate);
DateTime.TryParse(dPolicyPaidHistories[i].EndDate, out endDate);
Have to declare another variable and used as Out for TryParse.
必须声明另一个变量并用作TryParse 的Out。