在 ASP.NET Core-6 实体框架中,我使用通用存储库:
public interface IGenericRepository<T> where T : class
{
Task<T> GetByIdAsync(object id);
}
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
private readonly ApplicationDbContext _context;
internal readonly DbSet<T> _table;
public GenericRepository(ApplicationDbContext context)
{
_context = context;
_table = context.Set<T>();
}
public virtual async Task<T> GetByIdAsync(object id)
{
return await _table.FindAsync(id);
}
}
我收到此警告:
'_table' 这里不为空 通用存储库中可能返回空引用
我该如何解决这个问题?
谢谢你
答案在另一个堆栈交换网站上:https://softwareengineering.stackexchange.com/questions/433387/whats-wrong-with-returning-null
报价
您已启用 C# 的可空引用类型 (NRT) 功能。这要求您显式指定何时可以返回 null。因此将签名更改为:
public TEntity? Get(Guid id)
{
// Returns a TEntity on find, null on a miss
return _entities.Find(id);
}
警告就会消失。
我没有使用该功能,但希望您的代码应该如下所示
public virtual async Task<T?> GetByIdAsync(object id)
{
return await _table.FindAsync(id);
}
警告“可能返回 null 引用”是 C# 8.0 中的一项新功能,当您返回可能为 null 的值时,它会发出警告。当编译器无法确定方法返回的值永远不会为空时,就会生成警告。在您的代码中,会生成警告,因为 Find 方法返回 ProductColor 类型的对象,该对象可以为 null,并且可以为 null。要修复此警告,您可以使用 null 宽容运算符 (!) 告诉编译器您知道该值永远不会为 null,或者使用 null 合并运算符 (??) 在值为 null 时提供默认值。以下是如何使用 null-forgiving 运算符的示例:
public virtual async Task<T> GetByIdAsync(object id)
{
return await _table.FindAsync(id)!;
}
以下是如何使用空合并运算符的示例:
public virtual async Task<T> GetByIdAsync(object id)
{
return await _table.FindAsync(id)?? new Task<T>();
}
我希望这有帮助!
来源:与 Bing 对话,2023 年 8 月 23 日 (1) c# - 为什么此代码给出“可能的空引用返回...”。 为什么此代码给出“可能的空引用返回”编译器警告?。 (2) 解决可为空警告 |微软学习。 https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/nullable-warnings。 (3) 理解可能的空引用返回 - 堆栈内存溢出理解可能的空引用返回。