2016-08-15 65 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',构造函数被调用每次你创建一个新的类型值。你究竟想在这里实现什么? –

回答

相关问题