2011-09-01 77 views
-1

如何傳遞空值的方法傳遞空值的方法

[Import("Default", typeof(ISomeInterface), AllowRecomposition = true, AllowDefault = true)] 
public ISomeInterface x { get; set; } 
// x is null till now 
void DoWork(ISomeInterface obj) //Not working 
{ 
     if (obj == null) 
     { 
      //Download and Satisfy 
      DeploymentCatalog DC = new DeploymentCatalog("TheXAPfile.xap"); 
      DC.DownloadCompleted += (s, e) => 
      { 
       catalog.Catalogs.Add(f); //catalog is AggregateCatalog 
       obj.Show(); 
      }; 
      DC.DownloadAsync(); 
     } 
     else 
     { 
      obj.Show(); 
     } 

} 

由於

+0

什麼是不工作?你有一個實現'ISomeInterface'的值類型嗎? – dlev

+0

顯示發生實際錯誤的代碼部分以及它給出的消息(如果有),或者在編譯器錯誤時顯示編譯器消息。 –

+0

System.NullReferenceExcption:[Arg_NullRefrenceException] – MrBassam

回答

0

這裏你假設obj爲null,當您啓動異步下載,而且好歹它DownloadCompleted被觸發時沒有更多的空。你有沒有表現出保證你滿足這個條件? DownloadAsync之後你在做什麼,以及如何確保在完成下載之前評估這些內容?

if (obj == null) 
    { 
     //// you enter here only if obj is null 
     //Download and Satisfy 
     DeploymentCatalog DC = new DeploymentCatalog("TheXAPfile.xap"); 
     DC.DownloadCompleted += (s, e) => 
     { 
      catalog.Catalogs.Add(f); //catalog is AggregateCatalog 
      //// here you are assuming that obj is not null anymore. Why??? 
      obj.Show(); 
     }; 
     DC.DownloadAsync(); 
    } 
+0

+1這是有用的:是的,這簡直是使用'obj.Show();'當obj是顯然還是空所導致的問題。 EBKAC! –

+0

這是 我添加了這行 如果(ISomeInterface!= NULL)ISomeInterface.Show()的問題; 而且工作正常 謝謝:) – MrBassam

-2

這可以通過將實現?在函數頭中的對象類型之後。

void DoWork(ISomeInterface? obj) 
+4

除非'ISomeInterface'是一個可怕的命名值類型,這是不合法的,對引導來說也是多餘的(因爲接口變量已經可以爲null)。 – dlev

+1

實際上接口是引用類型,沒有必要在末尾添加'?'以傳遞'null' .. – Samich

1

例外是使用obj的某些方法或屬性爲空時的結果。你如果空來檢查自己的

void DoWork(ISomeInterface obj) //Not working 
{ 
    if(obj == null) 
    { 
     return; 
    } 
    /* do something ... */} 
} 
+0

這是正確的。這與可爲空的類型無關,但要自行檢查對象是否爲null。 –

+0

我謝謝:) – MrBassam