D 中的属性和 ref 返回值
在 D 中测试以下内容
import std.stdio;
struct S
{
int _val;
@property ref int val() { return _val; }
@property void val(int v) { _val = v; writeln("Setter called!"); }
}
void main()
{
auto s = S();
s.val = 5;
}
会产生 "Setter called!"
作为输出。
编译器使用什么规则来确定是调用第一个还是第二个实现?
Testing the following in D
import std.stdio;
struct S
{
int _val;
@property ref int val() { return _val; }
@property void val(int v) { _val = v; writeln("Setter called!"); }
}
void main()
{
auto s = S();
s.val = 5;
}
yields "Settter called!"
as the output.
What rule does the compiler use to determine whether to call the first or the second implementation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里您提供了两种
@property
方法,一种接受参数,另一种不接受。当执行s.val = 5;
时,您实际执行的是s.val(5)
,但由于val
是 < code>@property 您可以将其编写为属性而不是方法调用(请参阅http://d-programming-language.org/function.html#property-functions)。从s.val(5)
编译器可以执行标准重载解析 - 请参阅 http://d-programming-language.org/function.html#function-overloading。Here you are providing two
@property
methods, one accepts an argument, the other does not. When doings.val = 5;
, what you're actually doing iss.val(5)
, but asval
is a@property
you can write it as a property rather than a method call (see http://d-programming-language.org/function.html#property-functions). Froms.val(5)
the compiler can do standard overload resolution - see http://d-programming-language.org/function.html#function-overloading.