英文:
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<T>() {
print(T); // the actual type
print(T is ClockData); // ClockData is a class I created
// always returns false when passing _getCollection<ClockData>()
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<T>() {
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<T>() {
if (<T>[] is List<ClockData>) {
return 1;
} else if (<T>[] is List<UserData>) {
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论