是否可以在每个对象只调用一次的结构中有一个构造函数?例如,我希望代码的行为与此类似:
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
,但这不起作用。在测试ObjectIDGenerator
时,this
也不会。
答案 0 :(得分:0)
没有。你要的是静态构造函数。其本质上必须是无参数的。哪个结构构造器不可能。
msdn https://msdn.microsoft.com/en-us/library/aa288208(v=vs.71).aspx