简体   繁体   English

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

[英]Java - Do java have something like C#'s struct automatic constructor

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 ? 在java中有类似C#的struct自动构造函数吗?

What I mean is In C# 我的意思是在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
    }
}

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. 否 - Java根本不支持自定义值类型,并且始终显式调用构造函数。

However, your understanding of C# is incorrect anyway. 但是,无论如何,您对C#的理解是不正确的。 From your original post: 从你原来的帖子:

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

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: 您可以在没有任何显式初始化的情况下写入 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

No, you always need to explicitly call a constructor in Java. 不,您总是需要在Java中显式调用构造函数。

Since there may be multiple constructors, calling a specific constructor explicitly would probably be good practice anyway. 由于可能有多个构造函数,因此无论如何都要明确地调用特定的构造函数。

Java不支持Struct关键字(请参阅: http//msdn.microsoft.com/en-us/library/ms228600 (v = VS.90.aspx )因此您需要使用仅公开的类对象(没有函数。)你总是需要初始化类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM