如何检查Dart NNBD中的通用类型是否可为空? [英] How do I check whether a generic type is nullable in Dart NNBD?

查看:45
本文介绍了如何检查Dart NNBD中的通用类型是否可为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一些函数采用通用类型作为参数.如何在该函数中检查泛型类型参数是否可为空?我想做这样的事情:

Let's say I had some function that takes a generic type as an argument. How do I check within that function whether the generic type argument is nullable or not? I want do something like this:

void func<T>() {
  print(T is nullable);
}

void main(){
  func<int>(); //prints false
  func<int?>(); //prints true
}

我唯一想做的就是检查 T.toString()是否以?结尾,这很hacky.

All I can think of to do is to check if T.toString() ends with a ? which is very hacky.

推荐答案

尝试:

bool isNullable<T>() => null is T;

这篇关于如何检查Dart NNBD中的通用类型是否可为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆