我已经使用 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;
这不是真的。你可以write to mStruct.i
这里没有任何显式初始化,但你不能read除非编译器知道所有内容都已被赋值:
MyStruct x1;
Console.WriteLine(x1.i); // Error: CS0170: Use of possibly unassigned field 'i'
MyStruct x1 = new MyStruct();
Console.WriteLine(x1.i); // No error
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)