【问题标题】:Why is there nullability warning for explicitly declared reference return value?为什么显式声明的引用返回值存在可空性警告?
【发布时间】:2020-05-17 10:00:15
【问题描述】:

我为我的测试项目启用了可空性上下文并尝试修复所有可空性警告。除了以下我不理解的问题(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? 的不可空变量ref Book 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;
    }

为什么编译器会在第一个代码中产生 sn -p 这个错误:

Nullability of reference types in value of type 'Book' doesn't match target type 'Book?'.

【问题讨论】:

    标签: c# c#-8.0 nullable-reference-types nullability


    【解决方案1】:

    出现错误是因为您在此处使用ref returns。

    回忆ref returns 的含义。您正在返回对变量的引用,调用者可以使用该引用更改变量的值。

    GetBookByTitle 被声明为返回一个可为空的引用。根据声明,我可以从方法中获取引用,然后设置为null:

    ref var book = ref GetBookByTitle("Tale of Two Cities, A");
    book = null; // book is nullable, right? GetBookByTitle says it will return a nullable reference
    

    由于我传入的特定标题,将达到book = null;,将不可为空 books[1] 设置为null!如果允许这样做,就会破坏可空引用类型带来的安全性,因此是不允许的。

    【讨论】:

    • 哦,我没有想到这种情况。谢谢你的解释!
    猜你喜欢
    • 2020-04-20
    • 2011-11-08
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    相关资源
    最近更新 更多