[英]Java - Do java have something like C#'s struct automatic 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
}
}
是否可以強制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
不,您總是需要在Java中顯式調用構造函數。
由於可能有多個構造函數,因此無論如何都要明確地調用特定的構造函數。
Java不支持Struct關鍵字(請參閱: http : //msdn.microsoft.com/en-us/library/ms228600 (v = VS.90 ) .aspx )因此您需要使用僅公開的類對象(沒有函數。)你總是需要初始化類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.