簡體   English   中英

我應該如何處理使用塊中的空對象?

[英]How should I deal with null objects in a using block?

鑒於這樣的情況:

using (var foo = CreateFoo()) {
    if (foo != null) {
        // do stuff
    }
}

我想避免嵌套if。 遺憾的是,顯而易見的解決方案是不可能的,因為break不能用於:

using (var foo = CreateFoo()) {
    if (foo == null) {
        break;
    }
    // do stuff
}

是否有一種模式仍然可以避免由if != null引起的額外縮進?

如果你對從CreateFoo()返回的類有足夠的控制,你可以只實現一個Null對象並返回它而不是實際的NULL值

我贊成小明確命名的方法:

public void DoWhatEver()
{
   using (var foo = CreateFoo())
   {
     if (foo == null) return;

     //DoWhatEver
   }
}

介紹一個帶lambda的輔助方法。 所以你的代碼變成:

UsingIfNotNull(CreateFoo(), foo => {
  //do stuff
});

哪個有你想要的縮進。 UsingIfNotNull的定義是:

public static void UsingIfNotNull<T>(T item, Action<T> action) where T : class, IDisposable {
  if(item!=null) {
    using(item) {
      action(item);
    }
  }
}

這只是一個樣式問題......代碼很好。 你真的擔心縮進嗎? 這是另一種失去縮進的方法......

public void DoWhatEver()
{
   using(var foo = CreateFoo())
   {
       DoStuffWithFoo(foo);
   }

}

private void DoStuffWithFoo(Foo foo)
{
    if(foo == null) return;

    //DoWhatEver

}

在那種通用意義上,我相信我會將try...catch包裝在try...catch塊中並在對象為null時拋出異常,但這是個人偏好。

這是一個丑陋的黑客,但它避免了額外的身份:

do using (var foo = CreateFoo()) {
    if (foo == null) {
        break;
    }
    // do stuff
} while (false);

(不,我不建議這樣做。這只是一個概念驗證,表明它是可能的。)

如果可能的話,我建議改為重構你的代碼:

 using (var foo = CreateFoo()) {
    if (foo != null) {
        doSomethingWith(foo);  // only one line highly indented
    }
}

就個人而言,我可能會在您發布代碼時留下代碼。

但是,既然你問過(並且有可能讓自己暴露於這種經常被誹謗的語言特征),你可以隨時使用“goto”:

using (var foo = CreateFoo()) {
    if (foo == null) {
        goto SkipUsingBlock;
    }
    // do stuff
}

SkipUsingBlock:
// the rest of the code...

C#編譯器使用(var foo = CreateFoo())語句處理:

try
{
var foo = CreateFoo();
}
finally
{
  ((IDisposable) foo).Dispose();
}

如果您的方法CreateFoo返回不是一次性對象 - 請勿使用。 在其他情況下,你可以寫:

try
{
var foo = CreateFoo();
//do stuff like foo.SomeMethod (if foo == null exception will be thrown and stuff will not be done)
}
finally
{
  ((IDisposable) foo).Dispose();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM