我应该如何处理使用块中的空对象?

maf*_*afu 3 .net c# using code-readability

鉴于这样的情况:

using (var foo = CreateFoo()) {
    if (foo != null) {
        // do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

我想避免嵌套if.遗憾的是,显而易见的解决方案是不可能的,因为break不能用于:

using (var foo = CreateFoo()) {
    if (foo == null) {
        break;
    }
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)

是否有一种模式仍然可以避免由此引起的额外缩进if != null

yas*_*891 6

如果你对从CreateFoo()你返回的类有足够的控制,你可以实现一个Null对象并返回它而不是实际的NULL值