簡體   English   中英

是否存在檢查變量是 Nothing 還是 WhiteSpace 的方法?

[英]Does a method exist to check if a variable is Nothing or WhiteSpace?

C# 有String.IsNullOrWhiteSpace(String) ,我們有IsNothingOrWhiteSpace(String)嗎?

我已經搜索了文檔,它似乎不存在,但您可以自己編寫。

function IsNullOrWhiteSpace(verify::Any)
  # If verify is nothing, then the left side will return true.
  # If verify is Nothing, then the right side will be true. 
  return isnothing(verify) || isa(nothing,verify)
end 

function IsNullOrWhiteSpace(verify::AbstractString)
  return isempty(strip(verify))
end

println(IsNullOrWhiteSpace(nothing)) # true
println(IsNullOrWhiteSpace(" ")) # true

可能不是最好的方法,但它確實有效。

為什么我們需要isnothing()isa()

讓我們看看當我們將isnothing()nothingNothing一起使用時會發生什么。

println(isnothing(nothing)) # true
println(isnothing(Nothing)) # false

我們顯然想處理Nothing ,我們該怎么做呢?

使用isa() ,它將測試nothing是否是Nothing的類型。

比其他答案稍微優雅一點的方法是充分使用多重調度:

isNullOrWS(::Type{Nothing}) = true
isNullOrWS(::Nothing) = true
isNullOrWS(verify::AbstractString) = isempty(strip(verify))
isNullOrWS(::Any) = false

這實際上也導致了更快的匯編代碼。

julia> dat = fill(Nothing, 100);

julia> @btime isNullOrWS.($dat);
  174.409 ns (2 allocations: 112 bytes)

julia> @btime IsNullOrWhiteSpace.($dat);
  488.205 ns (2 allocations: 112 bytes)

暫無
暫無

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

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