我很想知道哪一個更好用,因爲我必須再次檢查它n再次在我的在C#代碼if(args.Length <1)和if(args.Length == 0 || args == null)之間的區別
if(args.Length<1) //i use
VS
if(args.Length == 0 || args == null)
作爲備用。
或VS如果事情可能像
if (args.exists) // or more simple?
我很想知道哪一個更好用,因爲我必須再次檢查它n再次在我的在C#代碼if(args.Length <1)和if(args.Length == 0 || args == null)之間的區別
if(args.Length<1) //i use
VS
if(args.Length == 0 || args == null)
作爲備用。
或VS如果事情可能像
if (args.exists) // or more simple?
首先從形式可能遭受NullReferenceException
如果args
是空 - 你不能訪問其Length
屬性。
第二種形式應該被反轉是正確的:
if (args == null || args.Length == 0) ...
第三種形式是語法不正確。你也許會想LINQ功能Any
的:
if (args.Any()) ...
但話又說回來,你必須要測試的空第一。
我不清楚你到底在測試什麼。如果您正在檢查陣列中是否有東西,則條件應如下所示:
if (args != null && args.Length > 0)
{
// Free to access args[0] here
}
兩者實際上都存在問題。
if(args.Length == 0 || args == null)
實際上應該是
if(args == null || args.Length == 0)
第一個將拋出一個NullReferenceException如果參數表是空。第二個不會由於C#的短路行爲(因爲一旦它看到參數爲空,它將停止評估表達式)。這個bug也影響到這一個:
if(args.Length<1)
隨着中說,
if(args == null || args.Length == 0)
的行爲一樣
if(args == null || args.Length<1)
,但我認爲,首先是更加清晰。
如果參數是string[]
您可以使用它作爲一個班輪。您正在使用Null-Conditional Operator,你需要使用C#6.0
if(args?.Any() == true)
{
//the code will go in this block if args != null and args has items in it.
}
編輯:就像在評論中提到這會爲每IEnumerable<T>
不應該爲任何'IEnumerable
@NicoSchertler是的,但我期望這是Console.Application其中的參數字符串[] – mybirthname
工作在C#中做一個&&
檢查將評估開始在左邊和如果第一個條件爲真,它將檢查右邊的其他條件。如果它是假的,它不會檢查其餘的。這被稱爲「短路」。
如果它正在執行||
它將從左邊開始,只要其中一個條件爲真,它就不會檢查其餘條件。
你有這樣的代碼:
if(args.Length == 0 || args == null)
C#將檢查args.Length
第一,並想如果參數表是空會發生什麼。例外。
如果您切換它們,它將首先檢查args == null
,如果它是真的,因爲您正在執行||
它將停止並且不執行下一個檢查。如果它不是null,那麼它將檢查下一個條件並且不會拋出異常。
因此,請牢記這些規則並巧妙地放置您的條件。
如果'args'爲null,這兩個都會拋出'NullReferenceException'。無論您需要檢查什麼,您都可以編寫包裝方法。就像'if(IsValid(args))...' –
@NicoSchertler基本上'NullReferenceException'是我提問的原因。 'IsValid'可能不可能,雖然... –