类型参数(C#)上的可空性属性

时间:2020-10-10 16:56:26

标签: c# nullable-reference-types

从文档中获取var fetchResultsController: NSFetchedResultsController<Item>! let request: NSFetchRequest<Item> = Item.fetchRequest() request.sortDescriptors = [NSSortDescriptor(key: "list.name", ascending: true)] fetchResultsController = NSFetchedResultsController<Item>(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: “list.name”, cacheName: nil) try? fetchResultsController?.performFetch() fetchResultsController?.delegate = self tableView.reloadData() 属性的主要原因是将其应用于泛型,其中不能使用[AllowNull]语法。但是,不允许在通用参数上指定T?

AllowNull

有什么办法可以使函数像这样吗?

void f<[AllowNull] T>() {} // error

更新:我明白为什么不允许这样做。由于空值分析与数据流相关,因此它仅允许在变量上使用。如何解决这个嵌套的泛型问题?

1 个答案:

答案 0 :(得分:0)

我最近得到的是

   [return: NotNullPost]
    public static T HasNoNulls<T, TT>([NotNullPost][AllowNull] T value)
        where T : IEnumerable<TT>
    {
        if (value.Any(e => e is null))
            throw new ArgumentException();
        return value;
    }

List<string?>? list = null;
// requires to specify types and use null assertion ↓
var ll = Check.HasNoNulls<List<string>, string>(list!, "");
ll[0].Trim(); // no warnings