飞镖代码:
class User() {
static onmystatic() {
printCurrentType(); // should print: User
}
}
Run Code Online (Sandbox Code Playgroud)
请注意printCurrentType()类中的User,是否可以实现它?我尝试过this.runtimeType,但它提醒我this不在范围内。
由于onmystatic()是静态的,它调用的任何函数都必须是静态的(或某个对象的实例方法),所以我假设printCurrentType()也是静态的。由于静态方法无法被重写,因此类型是常量,您可以编写:
class User {
static onmystatic() {
printCurrentType();
}
static printCurrentType() {
print(User);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想printCurrentType()成为某种泛型方法来打印调用它的任何静态方法的包含类的类型,那么......这是一项更加艰巨的任务。最简单的答案是不要尝试这样做并将类作为参数传递:
class User {
static onmystatic() {
printCurrentType(User);
}
}
printCurrentType(Type type) {
print(type);
}
Run Code Online (Sandbox Code Playgroud)
复杂的答案是,您可以抛出异常,解析堆栈跟踪,并尝试通过某些规则确定应该打印哪个类。我将把它作为练习留给读者:)
| 归档时间: |
|
| 查看次数: |
961 次 |
| 最近记录: |