有没有相当于Ruby的attr_accessor的d-lang

jar*_*ine 2 d

在Ruby中,我可以轻松地在类这样的类上设置读/写属性:

class Bar
  attr_accessor :foo, :bizz, :buzz
end
Run Code Online (Sandbox Code Playgroud)

这将是相同的

class Bar
  def foo
    @foo
  end

  def foo=(foo)
    @foo = foo
  end

  def bizz
    @foo
  end

  def bizz=(bizz)
    @bizz = bizz
  end

  def buzz
    @buzz
  end

  def buzz=(buzz)
    @buzz = buzz
  end
end
Run Code Online (Sandbox Code Playgroud)

相同的代码是D非常冗长,我发现自己在各处重复的事情:

class Bar {
  private {
    string _foo, _bizz, _buzz;
  }

  @property {
    string foo()  { return _foo;  }
    string bizz() { return _bizz; }
    string buzz() { return _buzz; }

    void foo(string foo)   { _foo = foo;   }
    void bizz(string bizz) { _bizz = bizz; }
    void buzz(string buzz) { _buzz = buzz; }
  }
}
Run Code Online (Sandbox Code Playgroud)

有这么简单的方法吗?

Ada*_*ppe 7

是:

public string foo;
Run Code Online (Sandbox Code Playgroud)

琐碎的财产访问者是浪费时间IMO.Ruby强迫你去做,但D没有.

无论如何,如果你想要它们,mixin模板可以完成这项工作:

mixin template attr_accessor(Type, string name) {
    static string codeGenerationHelper() {
        string code;
        // the variable
        code ~= "private Type _" ~ name ~ ";";

        // the getter
        code ~= "public @property Type " ~ name ~ "() { return _" ~ name ~ "; }";

        // the setter
        code ~= "public @property Type " ~ name ~ "(Type a) { return _" ~ name ~ " = a; }";

        return code;
    }

    mixin(codeGenerationHelper());
}

// here's how to use it
class Foo {
    mixin attr_accessor!(string, "foo");
}

void main() {
    auto foo = new Foo();
    foo.foo = "test";
}
Run Code Online (Sandbox Code Playgroud)