[英]Why doesn't C# null check work with structs?
我通常使用if (foo is not null)
檢查可空類型,然后我可以像使用非空類型一樣使用foo
。 為什么這不適用於結構? 甚至!
運營商沒有幫助。 這是一個錯誤還是我錯過了什么? 最短的解決方法是什么?
Foo? foo = new Foo { a = "foo" };
if (foo is not null) {
Console.WriteLine(foo.a); // Works, prints "foo"
}
Bar? bar = new Bar { a = "bar" };
if (bar is not null) {
Console.WriteLine(bar.a); // Error: Bar? does not contain a definition for "a"
Console.WriteLine(bar!.a); // Same error
}
class Foo {
public string a;
}
struct Bar {
public string a;
}
向后兼容。
可空值類型從 C# 2.0 開始存在,它們的實現方式不同於可空引用類型(自 C# 8.0 起)。
int?
是Nullable<int>
的同義詞,它是與int
完全不同的類型。 有一些編譯器魔法(提升的運算符)使其行為相似,但Nullable<int>
具有int
沒有的成員( HasValue
, Value
),反之亦然( ToString(string)
)。string?
另一方面,是string
類型,啟用了額外的編譯時檢查。 對int?
允許您訪問底層int
而無需使用.Value
“解包”它會破壞大量現有代碼。
但是,您可以使用模式匹配來創建具有基礎類型的新變量:
int? a = 3; // implicit conversion from int to Nullable<int>
if (a is int b)
{
// Use b to access the underlying int here.
}
else
{
// a was null
}
結構是值類型,不能賦值為 null。 通過將結構聲明為可為空,您可以將它們包裝在 Nullable<T> 結構中。 在您的情況下,您應該檢查 Nullable<Bar> 結構的 HasValue 和 Value 屬性。
Bar? bar = new Bar { a = "bar" };
if (bar.HasValue)
{
Console.WriteLine(bar.Value.a);
Console.WriteLine(bar.Value.a);
}
結構是一種值類型,因此它永遠不會為空。 您可以檢查 struct 的默認值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.