在 .NET 6.0 中使用 C# 我遇到警告說“無法將 null 文字轉換為不可為 null 的參考型別”。我認為類可以為空并且可以設定為空...
這會產生警告:
public class Foo
{
public string Name { get; set; }
public Foo()
{
Name = "";
}
}
public class Bar
{
public Foo fooClass;
public Bar()
{
// Because I don't want to set it as anything yet.
fooClass = null;
}
public void FooBarInit()
{
fooClass = new Foo();
}
}
但是這樣做沒有給我任何警告
public class Foo
{
public string Name { get; set; }
public Foo()
{
Name = "";
}
}
public class Bar
{
public Foo? fooClass;
public Bar()
{
// Because I don't want to set it as anything yet.
fooClass = null;
}
public void FooBarInit()
{
fooClass = new Foo();
}
}
但是現在讓我們嘗試在 Bar 內部的 Foo 中使用 Name 變數
public class Foo
{
public string Name { get; set; }
public Foo()
{
Name = "";
}
}
public class Bar
{
public Foo? fooClass;
public Bar()
{
// Because I don't want to set it as anything yet.
fooClass = null;
}
public void FooBarInit()
{
fooClass = new Foo();
}
public void FooBarTest()
{
Console.WriteLine(fooClass.Name); // Warning here which tells me fooClass maybe null
}
}
但是,如果沒有先運行 FooBarInit,FooBarTest 將永遠不會運行。所以它永遠不會為空,如果是的話,之后我會遇到錯誤處理情況。
我的問題是,為什么我必須將類設定為允許 null 當它們本來應該接受 null 時?
如果我使用“?” 在宣告一個類之后......我現在必須檢查它是否為空......任何時候我想呼叫那個類,它讓我的代碼看起來很糟糕。任何修復或關閉它的能力?
uj5u.com熱心網友回復:
雖然這是一個非常好的功能,但您仍然可以通過將Nullable屬性的值disable更改為.csproj檔案中的值來禁用它:
<PropertyGroup>
...
<Nullable>disable</Nullable>
...
</PropertyGroup>
uj5u.com熱心網友回復:
如果您知道可空型別的值不可能為 null,則可以使用null-forgiving operator。
Console.WriteLine(fooClass!.Name);
您還可以(奇怪的是,對于這個 Kotlin 開發人員)null使用這種機制分配給不可為空的型別:
public Foo fooClass = null!;
這個答案表明它類似于lateinit在 Kotlin 中使用,它對編譯器說“我保證在我開始使用它時它會被設定為非空值”。您可以使用此技術將變數初始化為 null,但以后不能將其設定為 null。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/514885.html
標籤:C#。网视觉工作室
