[英]Mocking a function with optional parameter with fixed parameter using Nsubstitute in C# returns null
[英]How to annotate a C# function to say that a parameter is not null if it returns
如果字符串為空/空/空白,我有一些驗證代碼會拋出異常。 我希望它在 function 返回后向 null 檢查系統發出信號,表明argument
不是 null。
void ThrowIfNullEmptyOrBlank(string? argument, string paramName)
=> ThrowIf(Check.Null & Check.Empty & Check.Blank, argument, paramName);
[return: NotNull] void ThrowIfNullEmptyOrBlank(string? argument, string paramName)
不對,因為我的方法沒有返回值(我想我可以改變它,但這樣更干凈)。
有可能做我正在嘗試的事情嗎?
只需使用NotNullAttribute
:
void ThrowIfNullEmptyOrBlank([NotNull] string? argument, string paramName)
=> ThrowIf(Check.Null & Check.Empty & Check.Blank, argument, paramName);
來自由 C# 編譯器解釋的空狀態 static 分析的屬性:
可為 null 的參數、字段、屬性或返回值永遠不會是 null。
這與目標相符——如果方法返回, argument
永遠不會是 null。
這個答案也很有用(也可以查看CallerArgumentExpressionAttribute
技巧)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.