C# 如何设置对象的初始状态,无';这';分配
我有一个属性为C# 如何设置对象的初始状态,无';这';分配,c#,C#,我有一个属性为Capacity的类,当Capacity=0时,对象必须设置为初始状态。我使用方法InitState()来实现这一点,因为我无法创建新实例并分配给this。是否有方法使用此或其他方法设置初始状态 public class Test { private int _field1 = -1; private int[] _array; ... public Test() : this(0) { } public Test(int capacity) {
Capacity
的类,当Capacity=0
时,对象必须设置为初始状态。我使用方法InitState()
来实现这一点,因为我无法创建新实例并分配给this
。是否有方法使用此或其他方法设置初始状态
public class Test {
private int _field1 = -1;
private int[] _array;
...
public Test() : this(0) { }
public Test(int capacity) {
_array = new int[capacity];
}
...
public int Capacity {
get { return _array.Length; }
set
{
//not working
//if(value == 0) this = new Test();
if(value == 0) InitState();
...
}
}
//sets fields in default state
private void InitState() {
_field1 = -1;
_array = new int[0];
...
}
}
不,您不能为此分配值,因此使用
this
可以确认代码是正确的您是指名为Test()
的默认构造函数吗?为什么需要创建对象的新实例?即使您认为它是错误的,但您走的方向是正确的。您的InitState
应该具有一个容量并初始化对象。从构造函数调用相同的InitState(capacity)
。您发现无法为this
指针赋值。再次调用init方法是浪费时间的,请调用数组。清除\u Array
上的。如果将类更改为struct,[则可以使用this=
符号替换当前实例][1]。[1]: