2010-09-28 62 views
4

因此,在C#中我最喜歡做的事情之一是:Java相當於以下靜態只讀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中?我想我可以做一個靜態的最終字段,但我不知道如何編寫初始化代碼。 Enums會成爲Java領域的更好選擇嗎?

謝謝!

回答

5

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

2

這是我怎麼會效仿它在Java中。

public static Foo CONSTANT; 

static { 
    CONSTANT = new Foo("some", "arguments", false, 0); 
    // you can set CONSTANT's properties here 
    CONSTANT.x = y; 
} 

使用static塊會做你所需要的。

或者你可以簡單地做:

public static Foo CONSTANT = new Foo("some", "arguments", false, 0);