2016-08-15 63 views
-1

是否可以在每個對象僅調用一次的結構中具有構造函數?例如,我想要的行爲類似於此的代碼:僅對每個對象調用一次Struct構造函數

struct mystruct { /*...*/ } 

//later on 
mystruct x = 5; //constructor called once, okay 
x = 6; //constructor called twice for this object, exception thrown 
mystruct y = 6; //different object, this is okay 
mystruct z; 
z = 7; //this is also okay since the definition didn't call the constructor 

這是可能在C#中嗎?如果沒有,是否有辦法模擬這種行爲?

我試過保留一個靜態字典this的和測試是否有新的this存在,但沒有奏效。當測試this的時候也不會ObjectIDGenerator

+0

'mystruct x = 5;'這可能嗎? – user3185569

+0

類似於這個'mystruct z;'調用默認的構造函數,如果它存在(一次)。 'mystruct z = 5'調用應該由你實現的'overloaded operator ='(不是構造函數)。 –

+0

你在說什麼?對於對象的任何特定實例,構造函數只被調用過一次;如果沒有一個好的[mcve],就不可能理解你所顯示的代碼甚至是做什麼,但是假設你有一個隱式轉換,允許你爲'mystruct'類型的變量賦值一個'int',構造函數被調用每次你創建一個新的類型值。你究竟想在這裏實現什麼? –

回答

相關問題