d需要外部上下文
我遇到了意想不到
问题,它似乎只发生在单元测试中
,而不是单元测试
外.
unittest {
class Ab {
int a;
string b;
static class Builder {
int _a;
string _b;
Builder a(int a) {
_a = a;
return this;
}
Builder b(string b) {
_b = b;
return this;
}
Ab build() {
Ab t = new Ab();
t.a = _a;
t.b = _b;
return t;
}
}
}
Ab ab = new Ab.Builder()
.a(1)
.b("ham")
.build();
assert(ab.a == 1);
assert(ab.b == "ham");
}
这将无法编译,并出现以下错误:需要外部环境指针
.
但是,如果移动
类定义到unittest
块之外,那么一切都可正常工作:
class Ab {
int a;
string b;
static class Builder {
int _a;
string _b;
Builder a(int a) {
_a = a;
return this;
}
Builder b(string b) {
_b = b;
return this;
}
Ab build() {
Ab t = new Ab();
t.a = _a;
t.b = _b;
return t;
}
}
}
unittest {
Ab ab = new Ab.Builder()
.a(1)
.b("ham")
.build();
assert(ab.a == 1);
assert(ab.b == "ham");
}
为什么只在单元测试
中声明类
时,才有该错误?
单元测试
只是可运行代码并具有局部变量
的特殊函数
.
它内部声明的类和结构
可调用
外部函数上下文
来,访问
这些局部上下文
.
把外部类
标记为"静"
,就可去掉该错误.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现