代码之家  ›  专栏  ›  技术社区  ›  DigitalZebra

Java等价于以下静态只读C代码?

  •  4
  • DigitalZebra  · 技术社区  · 15 年前

    因此,在C#我最喜欢做的事情之一是:

    public class Foo
    {
        public static readonly Bar1 = new Foo()
        {
            SomeProperty = 5,
            AnotherProperty = 7
        };
    
    
        public int SomeProperty
        {
             get;
             set;
        }
    
        public int AnotherProperty
        {
             get;
             set;
        }
    }
    

    谢谢!

    2 回复  |  直到 15 年前
        1
  •  6
  •   Community Mohan Dere    9 年前

    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;
    }
    

    Named Parameter idiom in Java

        2
  •  2
  •   jjnguy Julien Chastang    15 年前

    这就是我在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);