在 using 语句中使用 null IDisposable 值
Using a null IDisposable value with the using statement
以下代码在执行时不会产生错误:
using ((IDisposable)null) {
Console.WriteLine("A");
}
Console.WriteLine("B");
null 值是 using
'allowed' 吗? 如果是,它在哪里记录?
我见过的大多数 C# 代码都会创建一个 "dummy/NOP" IDisposable 对象 - 是否特别需要一个非空的 Disposable 对象?有过吗?
If/since null 是允许的,它允许在 inside using 语句中放置 null guard,而不是 before 或 around。
C# Reference on Using 没有提到空值。
是的,允许空值。 C# 5.0 规范的第 8.13 节 "The using statement" 说:
If a null
resource is acquired, then no call to Dispose
is made, and no exception is thrown.
规范然后为 using
形式的语句提供以下扩展
using (ResourceType resource = expression) statement
当 resource
是引用类型时(dynamic
除外):
{
ResourceType resource = expression;
try {
statement;
}
finally {
if (resource != null) ((IDisposable)resource).Dispose();
}
}
以下代码在执行时不会产生错误:
using ((IDisposable)null) {
Console.WriteLine("A");
}
Console.WriteLine("B");
null 值是 using
'allowed' 吗? 如果是,它在哪里记录?
我见过的大多数 C# 代码都会创建一个 "dummy/NOP" IDisposable 对象 - 是否特别需要一个非空的 Disposable 对象?有过吗?
If/since null 是允许的,它允许在 inside using 语句中放置 null guard,而不是 before 或 around。
C# Reference on Using 没有提到空值。
是的,允许空值。 C# 5.0 规范的第 8.13 节 "The using statement" 说:
If a
null
resource is acquired, then no call toDispose
is made, and no exception is thrown.
规范然后为 using
形式的语句提供以下扩展
using (ResourceType resource = expression) statement
当 resource
是引用类型时(dynamic
除外):
{
ResourceType resource = expression;
try {
statement;
}
finally {
if (resource != null) ((IDisposable)resource).Dispose();
}
}