在我的对象转换代码中,我有很多:
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);
}
等等...我不希望所有转换都因某些属性而失败,所以我不能将所有这些都放在一个 try block 中,但如果某些事情失败我需要记录并继续..
有没有办法压缩所有这些 try catch 东西?
遗憾的是我们不能用 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)
}
最佳答案
如果可用,您可以使用 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);
}
}
关于c# - 在 C# 中处理异常时,如何压缩大量小的 Try-Catch block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4400533/