我为测试项目启用了可空性上下文,并尝试修复所有可空性警告。除了下面我不了解的那一部分(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
对方法中作为nullable返回的non-nullable变量不满意ref Book?
据我所知,我们可以将不可为空的变量分配给可为空的变量,如下所示。如下面的代码所示,如果我Book book
在Book?
类型为的方法中返回non-ref变量,则编译器不会看到任何问题:
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?'.
发生错误是因为您在ref return
这里使用。
回顾ref return
s的含义。您正在将引用返回到变量,调用者可以使用引用来更改变量的值。
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
!如果允许这样做,则会破坏可为空的引用类型带来的安全性,因此是不允许的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句