爪哇 - 做java的有一些像C#的结构构造自动 [英] Java - Do java have something like C#'s struct automatic constructor
问题描述
我已经使用C#很长一段时间,现在我需要做Java的东西。
I've been using C# for a long time and now I need to do something in Java.
有什么样的C#结构自动构造在java中?
Is there something like C#'s struct automatic constructor in java ?
我的意思是
在C#
What I mean is In 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在声明中使用默认的构造函数
Is it possible to force java to use default constructor on declaration ?
推荐答案
没有? - Java不支持自定义值类型的所有和构造函数总是明确要求。
No - Java doesn't support custom value types at all, and constructors are always explicitly called.
不过,你的C#的理解是不正确反正。从你的原帖:
However, your understanding of C# is incorrect anyway. From your original post:
// Automatic constructor was invoked
// This line is same as MyStruct mStruct = new MyStruct();
MyStruct mStruct;
这是不正确的。你可以的写下来到 mStruct.i
这里没有任何明确的初始化,但你不能的阅读的,除非编译器知道一切都已经分配一个值:
That's not true. You can write to mStruct.i
without any explicit initialization here, but you can't read from it unless the compiler knows everything has been assigned a value:
MyStruct x1;
Console.WriteLine(x1.i); // Error: CS0170: Use of possibly unassigned field 'i'
MyStruct x1 = new MyStruct();
Console.WriteLine(x1.i); // No error
这篇关于爪哇 - 做java的有一些像C#的结构构造自动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!