为什么显式声明的参考返回值会出现可空性警告?

I enabled Nullability context for my test project and tried to fix all nullability warnings. I was able to fix them all except the below one which I don't understand (at return ref book; line). I pasted the warning in the comment at this line that the compiler produces:

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;
    }
}

I don't understand why the compiler is not satisfied with the non-nullable variable ref Book book that is returned in the method as nullable ref Book?

As I know we can assign non-nullable variables to nullable variables and it's presented below. And as the code below shows the compiler doesn't see any problems if I return non-ref Book book variable in the method with Book? type:

    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?'.

评论