Properties 为什么在D中使用@property?

Properties 为什么在D中使用@property?,properties,d,Properties,D,我试着想出来了 struct PropertyTest { @property int x() { return val; } @property void x( int newVal ) { val = newVal; } void test() { int j; j = x; x = 5; } private: int val; } 当我将@属性保留在外时,执行完全相同的操作。一切都很好。那

我试着想出来了

struct PropertyTest
{
    @property int x() { return val; }
    @property void x( int newVal ) { val = newVal; }

    void test()
    {
        int j;
        j = x;
        x = 5;
    }

private:
    int val;
}
当我将
@属性
保留在外时,执行完全相同的操作。一切都很好。那么,将函数声明为
@property
有什么意义呢


顺便说一句,我正在使用dmd2编译器

它允许您使用不带括号的无arg方法(如读取变量),并允许您调用不带括号的单个arg方法,这是您分配给变量的方式

@property int foo() { ... }
@property void bar(int x) { ... }

void main()
{
    bar = foo;
}

您应该指定
-property
作为编译器的命令行选项。

它们在没有
@property
的情况下工作的原因是
@property
是在允许属性方法语法之后添加的。将
-property
添加到DMD命令行将强制使用
@property
注释。出于向后兼容性的原因,它不是默认值。总有一天它会成为默认值(或者他们这么说),因此最好使用
-property
进行编译,以确保正确地进行注释。

目前的编译器比将来的编译器更加宽容。用@property标记getter和setter是一种证明未来的好方法。要了解未来的情况,请使用-property编译。