簡體   English   中英

C# 可空檢查驗證屬性不是 null

[英]C# nullable check verify that property is not null

我有一個復雜的 object 我想檢查是否有效。 我有一種檢查方法,但是 C# 可空性檢查不知道它們:

#nullable enable
...

bool IsValid(Thing? thing) 
{
    return thing?.foo != null && thing?.bar != null;
}

...

if(IsValid(thing)) 
{
   thing.foo.subProperty; // CS8602 warning: foo is possibly null here

有什么方法可以在這里應用 TypeScript 的類型門之類的東西嗎? 如果IsValid為真,那么我們知道thing.foo不是 null,但 C# 分析器無法看到 function 內部。 如果我內聯檢查它可以,但是我復制粘貼代碼,這是一個簡單的例子。

是否有任何注釋或模式可以讓我通過更復雜的檢查進行可空性分析?

您可以像這樣使用null-forgiving 運算符

if (IsValid(thing))
{
    thing.foo!.subProperty;
}

正如@JeroenMostert 指出的那樣,雖然它對您沒有幫助foo ,但替代方法是NotNullWhen屬性。

編譯器知道這里thing不是null ,但foo可能仍然是null

bool IsValid([NotNullWhen(true)] Thing? thing)
{
    return thing?.foo != null && thing?.bar != null;
}

if (IsValid(thing))
{
    thing.foo;
}

暫無
暫無

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

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