Java - Java有类似C#的struct自动构造函数

EOG*_*EOG 2 c# java constructor

我已经使用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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 6

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

但是,无论如何,您对C#的理解是不正确的.从你原来的帖子:

// Automatic constructor was invoked
// This line is same as MyStruct mStruct = new MyStruct();
MyStruct mStruct; 
Run Code Online (Sandbox Code Playgroud)

这不是真的.你可以在没有任何显式初始化的情况下写入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
Run Code Online (Sandbox Code Playgroud)