所以,在C#中,我最喜欢做的事情之一是:
public class Foo
{
public static readonly Bar1 = new Foo()
{
SomeProperty = 5,
AnotherProperty = 7
};
public int SomeProperty
{
get;
set;
}
public int AnotherProperty
{
get;
set;
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么用Java写这个?我想我可以做一个静态的final字段,但是我不知道如何编写初始化代码.Enums在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;
}
Run Code Online (Sandbox Code Playgroud)
关于枚举问题的第二部分:如果不知道代码的用途是什么,就不可能说出来.
以下主题讨论了在Java中模拟命名参数的各种方法:Java中的命名参数习惯用法