catch 块版本 C#6 和旧版本之间的区别
different between catch block version C#6 and older versions
在 C# 6 中,您可以编写以下代码:
try { }
catch (Exception e) when (e is NullReferenceException) { }
catch (Exception e) when (e is UnauthorizedAccessException) { }
但是上面的代码和下面的旧 C# 代码有什么不同?
try { }
catch (NullReferenceExceptione e) { }
catch (UnauthorizedAccessExceptione e) { }
对我来说旧版本看起来最短而且最好用。
But what's the different between code above and the older C# code below?
e
在 catch 的主体中将是 Exception
类型,而不是派生类型。
For me looks the older version the shortest and best to use.
然后使用它。
此处 when
关键字的全部意义在于,它允许您编写任意布尔表达式来确定是否匹配,而不是 only 能够根据表达式是否为给定的派生类型来过滤表达式。
在您的示例中,除了在 catch 中键入 e
外,没有什么不同。
该关键字更多地用于简单的真/假检查,例如:
try
{
// Do stuff
}
catch (Exception e) when (
(DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
|| (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)) {
// Swallow
}
在 C# 6 中,您可以编写以下代码:
try { }
catch (Exception e) when (e is NullReferenceException) { }
catch (Exception e) when (e is UnauthorizedAccessException) { }
但是上面的代码和下面的旧 C# 代码有什么不同?
try { }
catch (NullReferenceExceptione e) { }
catch (UnauthorizedAccessExceptione e) { }
对我来说旧版本看起来最短而且最好用。
But what's the different between code above and the older C# code below?
e
在 catch 的主体中将是 Exception
类型,而不是派生类型。
For me looks the older version the shortest and best to use.
然后使用它。
此处 when
关键字的全部意义在于,它允许您编写任意布尔表达式来确定是否匹配,而不是 only 能够根据表达式是否为给定的派生类型来过滤表达式。
在您的示例中,除了在 catch 中键入 e
外,没有什么不同。
该关键字更多地用于简单的真/假检查,例如:
try
{
// Do stuff
}
catch (Exception e) when (
(DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
|| (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)) {
// Swallow
}