因此,在 C# 中,我最喜欢做的事情之一是:
public class Foo
{
public static readonly Bar1 = new Foo()
{
SomeProperty = 5,
AnotherProperty = 7
};
public int SomeProperty
{
get;
set;
}
public int AnotherProperty
{
get;
set;
}
}
我如何用 Java 编写这个?我在想我可以做一个静态的最终字段,但是我不确定如何编写初始化代码。枚举在 Java 领域会是更好的选择吗?
谢谢!
最佳答案
Java 没有与 C# 对象初始值设定项等效的语法,因此您必须执行以下操作:
public class Foo {
public static final Foo Bar1 = new Foo(5, 7);
public Foo(int someProperty, int anotherProperty) {
this.someProperty = someProperty;
this.anotherProperty = anotherProperty;
}
public int someProperty;
public int anotherProperty;
}
关于关于枚举的问题的第二部分:如果不知道您的代码的目的是什么,那是不可能说的。
以下线程讨论了在 Java 中模拟命名参数的各种方法:Named Parameter idiom in Java
关于Java 等效于以下静态只读 C# 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3809448/