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

时间:2014-04-23 22:48:15

标签: d

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

class Bar
  attr_accessor :foo, :bizz, :buzz
end

这与

相同
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

相同的代码是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; }
  }
}

有这么简单的方法吗?

1 个答案:

答案 0 :(得分:7)

是:

public string foo;

琐碎的财产访问者浪费时间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";
}