Dart:检查泛型函数的类型 T

huangapple go评论54阅读模式
英文:

Dart: Check Type T of generic function

问题

I have a generic function. I'm trying to return a value based on the type T,
however, my function never seems to match any types (see code below):

int _getCollection<T>() {
    print(T); // 实际类型
    print(T is ClockData); // ClockData 是我创建的一个类

    // 当传递 _getCollection<ClockData>() 时,始终返回 false
    if (T is ClockData) { 
      return 1;
    } else if (T is UserData) {
      return 2;
    } else {
      throw Exception();
    }
}
英文:

I have a generic function. I'm trying to return a value based on the type T,
however, my function never seems to match any types (see code below):

int _getCollection&lt;T&gt;() {
    print(T); // the actual type
    print(T is ClockData); // ClockData is a class I created

    // always returns false when passing _getCollection&lt;ClockData&gt;()
    if (T is ClockData) { 
      return 1;
    } else if (T is UserData) {
      return 2;
    } else {
      throw Exception();
    }
  }

答案1

得分: 2

is 运算符将检查左操作数是否是右操作数的实例。T 是一个类型参数,而不是 ClockData 的实例。您可以使用 == 运算符来比较它们:

int _getCollection<T>() {
  if (T == ClockData) { 
    return 1;
  } else if (T == UserData) {
    return 2;
  } else {
    throw Exception();
  }
}

请注意,这检查的是身份,不支持子类型。如果您需要支持类型继承(将 ClockData 的子类作为 T 传递),您可以使用以下技巧:

int _getCollection<T>() {
  if (<T>[] is List<ClockData>) {
    return 1;
  } else if (<T>[] is List<UserData>) {
    return 2;
  } else {
    throw Exception();
  }
}
英文:

is operator will check if left operand is an instance of right operand. T is a type parameter and not an instance of ClockData. You can use == operator to compare those:

int _getCollection&lt;T&gt;() {
  if (T == ClockData) { 
    return 1;
  } else if (T == UserData) {
    return 2;
  } else {
    throw Exception();
  }
}

Please not this checks for identity and will not support subtypes. If you need to support type inheritance (passing subclasses of ClockData as T) you can use a trick like this:

int _getCollection&lt;T&gt;() {
  if (&lt;T&gt;[] is List&lt;ClockData&gt;) {
    return 1;
  } else if (&lt;T&gt;[] is List&lt;UserData&gt;) {
    return 2;
  } else {
    throw Exception();
  }
}

答案2

得分: 2

The class type of T is actually Type. It's value is ClockData.

is checks for Runtimetype and T has runtime type of Type. So T is not ClockData.

as @fsw mentioned, == is much better approach.

英文:

The class type of T is actually Type. It's value is ClockData.

is checks for Runtimetype and T has runtime type of Type. So T is not ClockData.

as @fsw mentioned, == is much better approach.

huangapple
  • 本文由 发表于 2023年7月18日 16:12:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定