How project Lombok in java works and is that possible in .net using attributes?

牧云@^-^@ 提交于 2020-12-04 18:00:07

问题


Project Lombok makes it trivial to implement the boilerplate code in the classes. Is that possible with .NET attributes? Is any .net port there?


回答1:


Well in Lombok a Java class might look like this

import lombok.Data;

@Data public class Cart {
  private int id;
  private DateTime created;
  private int items;
  private int status;
}

While in C# the same class would look like this

public class Cart {
  public int Id { get; set; }
  public DateTime Created { get; set; }
  public int Items { get; set; }
  public int Status { get; set; }
}

So C# (3.0 in this example) gets rather close without any other libraries, but as you start adding "final" to some properties the magic "auto constructor" part of Lombok really shines. As for a .Net alternative, as I understand it the .Net annotations don't provide the ability to intercept the byte code before it goes to the compiler (what Lombok uses to such great effect), so your options are limited to some template system + a build script like nAnt. This would be a mess to maintain.




回答2:


I would say:

public class Cart {
   public int Id { get; set; }
   public DateTime Created { get; set; }
   public int Items { get; set; }
   public int Status { get; set; }
}
var cart = new Cart
{
   Id = 10,
   DateTime = DateTimeNow,
   ....
};

Dont need any builder per se. Just use c# object initializer? That said, it does not hide any implementation stuff. So if you would like to put some "factoring" of more complex init data to your init, you can hide that in the builder, but not directly in the object initializer. You must put that somewhere in the getter, or a helper class. The Lombok java generator does not either by the way. And the object initializer does not do any fluent stuff either, like .id(..).name() etc.



来源:https://stackoverflow.com/questions/3959646/how-project-lombok-in-java-works-and-is-that-possible-in-net-using-attributes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!