使用trycatchthrow定义类似tryparse的方法 [英] Define method like tryparse with trycatchthrow
问题描述
问题是,我想要将方法定义为类似于tryparse
private bool TryParse(字符串值,输出bool等)
{
试试
{
int.Parse(value);
}
catch(例外)
{
throw;
}
我尝试了什么:
私人bool TryParse(字符串值,out bool等)
{
试试
{
int.Parse(value);
etc = true;
返回true;
}
catch(例外)
{etc = false;
return = false;
throw;
}
如果你希望你的代码像.net TryParse方法一样,那就不要抛出异常。
private bool TryParse(string value,out bool等)
{
try
{
int.Parse(value);
等= true;
返回true;
}
catch(例外)
{etc = false;
return = false;
}
但是你的代码实际上只是检查字符串值是否可以转换为int。如果我是你,我会使用.net方法
私人bool TryParse(字符串值,输出bool等)
{
int x = 0;
返回int.TryParse(value,out x);
}
尽管他们的名字.netTryParse方法在内部不使用try\catch块作为例外提高成本很高,他们的目的是智能地解析文本,因此不需要引发异常。
Question is that want me to define method as tryparse like that
private bool TryParse(string value,out bool etc)
{
try
{
int.Parse(value);
}
catch (Exception)
{
throw;
}
What I have tried:
private bool TryParse(string value,out bool etc)
{
try
{
int.Parse(value);
etc = true;
return true;
}
catch (Exception)
{etc = false;
return = false;
throw;
}
If you want your code to act like the .net TryParse methods then don't "throw" the exception.
private bool TryParse(string value,out bool etc) { try { int.Parse(value); etc = true; return true; } catch (Exception) {etc = false; return = false; }
However your code is really just checking if the string value can be converted to an int. If I was you I'd use the .net method
private bool TryParse(string value,out bool etc) { int x = 0; return int.TryParse(value, out x); }
Despite their name The .net "TryParse" methods don't use try\catch blocks internally as exceptions are expensive to raise, their aim is to parse the text intelligently so an exception doesn't need to be raised.
这篇关于使用trycatchthrow定义类似tryparse的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!