【问题标题】:Java equivalent of the following static readonly C# code?Java 等效于以下静态只读 C# 代码?
【发布时间】:2011-04-18 02:09:53
【问题描述】:

所以,在 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 领域会是更好的选择吗?

谢谢!

【问题讨论】:

    标签: java .net static


    【解决方案1】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-01
        • 2017-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-18
        相关资源
        最近更新 更多