我为我的测试项目启用了可空性上下文并尝试修复所有可空性警告。除了以下我不理解的(return ref book;
在线)之外,我能够修复它们。我在编译器生成的这一行的注释中粘贴了警告:
class Program
{
private Book[] books = { new Book("Call of the Wild, The", "Jack London"),
new Book("Tale of Two Cities, A", "Charles Dickens") };
private Book? nobook = null;
public ref Book? GetBookByTitle(string title)
{
for (int ctr = 0; ctr < books.Length; ctr++)
{
ref Book book = ref books[ctr];
if (title == book.Title)
return ref book; //CS8619: Nullability of reference types in value of type 'Book' doesn't match target type 'Book?'.
}
return ref nobook;
}
}
public class Book
{
public readonly string Title;
public readonly string Author;
public Book(string title, string author)
{
Title = title;
Author = author;
}
}
ref Book book
我不明白为什么编译器对方法中返回的可空变量不满意ref Book?
据我所知,我们可以将不可为空的变量分配给可空的变量,如下所示。正如下面的代码所示,如果我在具有类型的方法中返回非引用Book book
变量,编译器不会发现任何问题:Book?
public Book? GetBookCopyByTitle(string title)
{
for (int ctr = 0; ctr < books.Length; ctr++)
{
ref Book book = ref books[ctr];
if (title == book.Title)
return book; //no warning here. The compiler is satisfied if we don't use ref return value
}
return null;
}
为什么编译器会在第一个代码片段中产生此错误:
Nullability of reference types in value of type 'Book' doesn't match target type 'Book?'.