我如何 "hard-code" 检查 void 类型的相等性?
how do I "hard-code" check equality for type void?
如何“硬编码”检查 void 类型的相等性?
这段代码运行得很好
class Foo<T> {
Type get ofType => T;
bool isType<S>() => T == S;
}
final _foo = Foo<void>();
void main() {
print(_foo.ofType);
print(_foo.isType<void>());
}
但这甚至无法编译
class Foo<T> {
Type get ofType => T;
bool isTypeVoid() => T == void;
}
final _foo = Foo<void>();
void main() {
print(_foo.ofType);
print(_foo.isTypeVoid());
}
lib/main.dart:3:29:
Error: Expected an identifier, but got 'void'.
bool isTypeVoid() => T == void;
^^^^
lib/main.dart:3:33:
Error: Expected an identifier, but got ';'.
bool isTypeVoid() => T == void;
^
lib/main.dart:3:29:
Error: Expected ';' after this.
bool isTypeVoid() => T == void;
^^^^
lib/main.dart:3:29:
Error: Expected a class member, but got 'void'.
bool isTypeVoid() => T == void;
^^^^
Error: Compilation failed.
如果您想知道
,我需要在 assert()
中硬编码 T == void
assert(T == void)
但不起作用
似乎没有解决办法
这是一些参考资料 [ 1, 2(第 216-217 页)]
至于这是一个答案,但不是解决方案
我可以提供 nonsense
解决方法
class Nonsense<T> {
const Nonsense();
Type call() => T;
}
const _voidType = Nonsense<void>();
class Foo<T> {
Type get ofType => T;
bool isTypeVoid() => T == _voidType();
}
final _foo = Foo<void>();
void main() {
print(_foo.ofType);
print(_foo.isTypeVoid());
}
感谢 discord 上的灾难指导
如何“硬编码”检查 void 类型的相等性?
这段代码运行得很好
class Foo<T> {
Type get ofType => T;
bool isType<S>() => T == S;
}
final _foo = Foo<void>();
void main() {
print(_foo.ofType);
print(_foo.isType<void>());
}
但这甚至无法编译
class Foo<T> {
Type get ofType => T;
bool isTypeVoid() => T == void;
}
final _foo = Foo<void>();
void main() {
print(_foo.ofType);
print(_foo.isTypeVoid());
}
lib/main.dart:3:29:
Error: Expected an identifier, but got 'void'.
bool isTypeVoid() => T == void;
^^^^
lib/main.dart:3:33:
Error: Expected an identifier, but got ';'.
bool isTypeVoid() => T == void;
^
lib/main.dart:3:29:
Error: Expected ';' after this.
bool isTypeVoid() => T == void;
^^^^
lib/main.dart:3:29:
Error: Expected a class member, but got 'void'.
bool isTypeVoid() => T == void;
^^^^
Error: Compilation failed.
如果您想知道
,我需要在assert()
中硬编码 T == void
assert(T == void)
但不起作用
似乎没有解决办法 这是一些参考资料 [ 1, 2(第 216-217 页)]
至于这是一个答案,但不是解决方案
我可以提供 nonsense
解决方法
class Nonsense<T> {
const Nonsense();
Type call() => T;
}
const _voidType = Nonsense<void>();
class Foo<T> {
Type get ofType => T;
bool isTypeVoid() => T == _voidType();
}
final _foo = Foo<void>();
void main() {
print(_foo.ofType);
print(_foo.isTypeVoid());
}
感谢 discord 上的灾难指导