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

标签 java .net static

因此,在 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/

相关文章:

java - JNA 中基于 C 的嵌套数组结构转换

c# - 为什么添加操作在 Mock 上不起作用?

c# - 在 C# 中向 CSS 类选择器添加属性

java - 什么是 "static"以及在哪里使用它?

java - 从静态外部 util 函数访问内部类

java - 理解多个for循环之间的相互关系

java - 如何打印一系列从 1 小于 x 到 0 结束的数字?

java - 正则表达式不接受空格

c# - 在 C# 中显示分层数据

java - 如何在使用 java 类之前加载静态初始化?