2017-01-03 29 views
0

我有一個函數:對象爲空用於string.Any(F =>)

public bool IsValidFileSelection(string[] fileNames) 
{ 
    bool isValid = false; 

    // There is no need to check the file types here. 
    // As it is been restricted by the openFileBrowse 

    if (fileNames != null && fileNames.Count() > 0) 
    { 
     if (fileNames.Count() == 1 && 
      fileNames.Any(f => Path.GetExtension(f) == ".jpg" 
           || Path.GetExtension(f) == ".png")) 
     { 
      isValid = true; 
     } 
     else 
     { 
      // If multiple files are there. none shoulf be of type .lfa 
      isValid = fileNames.Any(f => Path.GetExtension(f) == ".jpg" 
           || Path.GetExtension(f) == ".png"); 
     } 
    } 

    return isValid; 
} 

我似乎無法找出爲什麼我的使用串[]中的任何(F => Path.GetExtension(。 f)爲f返回一個空對象我正在使用它來試圖查看我的多選打開文件對話框中的文件對象是否都是jpg或png,因爲這是我想允許的唯一類型。路要走這個?爲什麼我對象(六)空?

+4

那麼想必' fileNames'包含一個空值。但目前你的邏輯很奇怪。爲什麼所有對「Count()」的調用?爲什麼兩個不同地方的情況相同?爲什麼在評論中引用lfa文件,然後不在代碼中? –

+0

爲什麼即使有內部的'如果'?無論是否有一個或多個,「Any」檢查都會起作用。 –

+1

該代碼可以大大簡化。對於初學者來說,'fileNames.Count()'應該是'fileNames.Length',並且在你檢查'fileNames.Length == 1'的地方,之後沒有理由使用LINQ,因爲你剛剛確認'fileNames '只包含一個可以被'fileNames [0]'引用的成員。 – Abion47

回答

2

這裏是我將簡化這一點,並使其更快(以避免uncessary調用.Any().Count()

class Program 
{ 
    static readonly string[] valid_ext = new[] { ".jpg", ".png" }; 

    public bool IsValidFileSelection(params string[] filenames) 
    { 

     if(filenames==null) return false; 
     if(filenames.Length==0) return false; 

     foreach(var item in filenames) 
     { 
      if(string.IsNullOrEmpty(item)) return false; 
      if(!valid_ext.Contains(Path.GetExtension(item))) 
      { 
       return false; 
      } 
     } 
     return true; 
    } 
} 

,這裏是測試套件我用

static void Main(string[] args) 
    { 
     var p = new Program(); 

     Debug.Assert(p.IsValidFileSelection()==false); 
     Debug.Assert(p.IsValidFileSelection("a.jpg")==true); 
     Debug.Assert(p.IsValidFileSelection("a.png")==true); 
     Debug.Assert(p.IsValidFileSelection("a.jpg", "a.png")==true); 
     Debug.Assert(p.IsValidFileSelection("a.jpg", "a.png", "a.lfa")==false); 
     Debug.Assert(p.IsValidFileSelection("a.lfa")==false); 
     Debug.Assert(p.IsValidFileSelection("a.png",null)==false); 
    } 
+1

您可能還想在其中包含'item == null'檢查,因爲OP的問題涉及'filenames'中的對象爲空。 – Abion47

+0

哦,是的。我忘了。我正在編輯。謝謝@ Abion47 – ja72

+0

正如我所看到的,你忽略數組中的* all *,而是最後一項*,這就是爲什麼你可以將整個循環改爲'LastOrDefault'命令。 –

0

一個解決方案已被選中,但爲了完整起見,我將包括LINQ選項:

public bool IsValidFileSelection(params string[] filenames) 
{ 
    if (filenames == null || filenames.Length == 0) 
     return false; 

    return filenames.All(f => f != null && 
       (Path.GetExtension(f) == ".jpg" || Path.GetExtension(f) == ".png")) 
}