Ale*_*sev 7 .net c# exception-handling exception try-catch
在我的对象转换代码中,我有很多:
try
{
NativeObject.Property1= int.Parse(TextObject.Property1);
}
catch (Exception e)
{
Trace.WriteLineIf(ConverterSwitch.TraceVerbose, e);
}
try
{
NativeObject.Property2= DateTime.Parse(TextObject.Property2);
}
catch (Exception e)
{
Trace.WriteLineIf(ConverterSwitch.TraceVerbose, e);
}
Run Code Online (Sandbox Code Playgroud)
等等...我不希望所有转换都失败导致某些属性因此我不能将所有这些放在一个try块中,但我需要记录一些事情是否失败并继续..
有没有办法压缩所有这尝试抓东西?
可惜我们不能用C#编写代码:
try
{
int num = int.Parse("3");
decimal num2 = decimal.Parse("3.4");
}
catch (Exception e)
{
Trace.Write(e);
continue; //continue execution from the point we left. (line 2)
}
Run Code Online (Sandbox Code Playgroud)
Bob*_*ack 12
您可以使用TryParse方法(如果可用).请参阅以下用于解析Int32值的示例代码.
private static void TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
Run Code Online (Sandbox Code Playgroud)
不,但你可以:
private static void ExecuteAndCatchException(Action action)
{
try
{
action();
}
catch (Exception e)
{
Trace.Write(e);
}
}
Run Code Online (Sandbox Code Playgroud)
然后
ExecuteAndCatchException(() => NativeObject.Property1 = int.Parse(TextObject.Property1));
ExecuteAndCatchException(() => NativeObject.Property2 = DateTime.Parse(TextObject.Property2));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1346 次 |
| 最近记录: |