我应该如何处理 using 块中的空对象?
鉴于这样的情况:
using (var foo = CreateFoo()) {
if (foo != null) {
// do stuff
}
}
我想避免嵌套的 if。遗憾的是,明显的解决方案是不可能的,因为 Break 不适用于 using:
using (var foo = CreateFoo()) {
if (foo == null) {
break;
}
// do stuff
}
是否有一种模式仍然可以避免由 if != null
引起的额外缩进?
Given a situation like this:
using (var foo = CreateFoo()) {
if (foo != null) {
// do stuff
}
}
I would like to avoid the nested if. Sadly, the obvious solution is not possible because break does not work with using:
using (var foo = CreateFoo()) {
if (foo == null) {
break;
}
// do stuff
}
Is there a pattern to still avoid the additional indentation caused by the if != null
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果您对从
CreateFoo()
返回的类有足够的控制,您可以实现一个 空对象 并返回此值而不是实际的 NULL 值If you have sufficient control over the class returned from
CreateFoo()
you could just implement a Null Object and return this instead of the actual NULL value我喜欢命名明确的小方法:
I favor small clearly named methods:
引入一个采用 lambda 的辅助方法。所以你的代码变成:
其中有你想要的缩进。 UsingIfNotNull 的定义是:
Introduce a helper method that takes a lambda. So your code becomes:
which has the indentation you want. The definition of UsingIfNotNull is:
这只是一个风格问题......代码很好。您真的那么担心缩进吗?无论如何,这是另一种丢失缩进的方法......
This is just a style issue ... code is fine. Are you really that worried about indents? Here's another way to lose the indents anyway ...
在这种一般意义上,我相信我会将 using 包装在 try...catch 块中,并在对象为 null 时抛出异常,但这是个人偏好。
In that sort of generic sense, I believe I would wrap the using in a
try...catch
block and throw an exception if the object was null, but that's a personal preference.就我个人而言,我可能会保留您发布的代码。
然而,既然你问了(并且冒着让自己对这个经常被诟病的语言功能投反对票的风险),你总是可以使用“goto”:
Personally I would probably leave the code as you've posted it.
However, since you asked (and at the risk of exposing myself to downvotes to this often-maligned language feature), you could always use "goto":
这是一个丑陋的黑客,但它避免了额外的标识:(
不,我不建议这样做。这只是一个概念证明,表明它是可能的。)
如果可能,我建议重构您的代码反而:
It's an ugly hack, but it avoids the additional identation:
(No, I don't recommend to do this. This is just a proof-of-concept to show that it's possible.)
If possible, I would suggest to refactor your code instead:
C# 编译器将 using(var foo = CreateFoo()) 语句视为:
如果您的方法 CreateFoo 返回的不是一次性对象 - 根本不要使用 using。在其他情况下你可以写:
C# compiler treats using(var foo = CreateFoo()) statement in:
If your method CreateFoo return not disposable object - do not use using at all. In other case you can write: