我已经使用C#很久了,现在我需要用Java做一些事情。

java中是否有类似C#的struct自动构造函数的东西?

我的意思是
在C#中

struct MyStruct
{
    public int i;
}
class Program
{
    void SomeMethod()
    {
        MyStruct mStruct; // Automatic constructor was invoked; This line is same as MyStruct mStruct = new MyStruct();
        mStruct.i = 5;   // mStruct is not null and can i can be assigned
    }
}


是否可以强制Java在声明时使用默认构造函数?

最佳答案

否-Java根本不支持自定义值类型,并且总是显式调用构造函数。

但是,您对C#的理解仍然是错误的。从您的原始帖子:

// Automatic constructor was invoked
// This line is same as MyStruct mStruct = new MyStruct();
MyStruct mStruct;


这不是真的。您可以在不进行任何显式初始化的情况下写入mStruct.i,但是除非编译器知道所有内容都已分配了值,否则您无法读取它:

MyStruct x1;
Console.WriteLine(x1.i); // Error: CS0170: Use of possibly unassigned field 'i'

MyStruct x1 = new MyStruct();
Console.WriteLine(x1.i); // No error

09-30 15:19
查看更多