如何检查类型参数是否是Dart中的特定类型?

问题描述 投票:2回答:3

我有一些Dart代码,我希望在泛型类型的参数是Stream的情况下实现特殊行为。

它是这样的:

class MyType<A> {
    A doit() {
        if (A is Stream) // doesn't work!
        else something-else;
    }
}

这可能吗?

dart
3个回答
1
投票

你不能使用A is Stream,因为A实际上是一个Type实例。但是你可以使用if (A == Stream)或虚拟实例if (new Stream() is A)


0
投票

要检查类型参数是否是特定类型,可以使用bool isTypeOf<ThisType, OfType>()包中的type_helper函数。如果此类型相同或者是其他的子类型,则返回true,否则返回false

import 'dart:async';

import 'package:type_helper/type_helper.dart';

void main() {
  if (isTypeOf<B<int>, A<num>>()) {
    print('B<int> is type of A<num>');
  }

  if (!isTypeOf<B<int>, A<double>>()) {
    print('B<int> is not a type of A<double>');
  }

  if (isTypeOf<String, Comparable<String>>()) {
    print('String is type of Comparable<String>');
  }

  var b = B<Stream<int>>();
  b.doIt();
}

class A<T> {
  //
}

class B<T> extends A<T> {
  void doIt() {
    if (isTypeOf<T, Stream>()) {
      print('($T): T is type of Stream');
    }

    if (isTypeOf<T, Stream<int>>()) {
      print('($T): T is type of Stream<int>');
    }
  }
}

结果:

B<int> is type of A<num> B<int> is not a type of A<double> String is type of Comparable<String> (Stream<int>): T is type of Stream (Stream<int>): T is type of Stream<int>


0
投票

你通常可以使用A == Stream,但你说在你的情况下,你有Stream<SomeType>

如果type始终为Stream,则可以使用您拥有的type参数创建一个虚拟实例:

class MyType<A> {
  A doit() {
    final instance = Stream<A>();

    if (instance is Stream<SomeType>) { // ... }
    else if (instance is Stream<OtherType>) { // ... }
  }
© www.soinside.com 2019 - 2024. All rights reserved.