[英]question about constructors in C#
你好
关于名为Square的类中的部分代码:
public Square( int i_RowIndex, eColumn i_ColIndex)
{
m_RowIndex = i_RowIndex;
m_ColIndex = i_ColIndex;
**new Square(i_RowIndex, i_ColIndex, eCoinType.NoCoin);**
}
public Square(int i_RowIndex, eColumn i_ColIndex, eCoinType i_CoinType)
{
m_RowIndex = i_RowIndex;
m_ColIndex = i_ColIndex;
m_Coin = i_CoinType;
}
在其他C'tor中调用过载的C'tor以及用粗体看到的“新”声明是不是很好? 我认为这是错误的,每次我们调用new时我们都会分配一个新实例,从C'tor分配2个重复实例是不对的,这意味着从第一个位置分配一个实例。
我错了吗?
谢谢
您不应该在构造函数中调用重载构造函数,而是创建一个新实例。
应该更像是:
public Square( int i_RowIndex, eColumn i_ColIndex)
: this(i_RowIndex, i_ColIndex, eCoinType.NoCoin)
{
}
public Square(int i_RowIndex, eColumn i_ColIndex, eCoinType i_CoinType)
{
m_RowIndex = i_RowIndex;
m_ColIndex = i_ColIndex;
m_Coin = i_CoinType;
}
这是不对的。 其实这句话:
new Square(i_RowIndex, i_ColIndex, eCoinType.NoCoin);
在构造函数上绝对没有 (有用)。
我认为你想要的是更像这样的东西:
public Square( int i_RowIndex, eColumn i_ColIndex)
: this(i_RowIndex, i_ColIndex, eCoinType.NoCoin)
{}
public Square(int i_RowIndex, eColumn i_ColIndex, eCoinType i_CoinType)
{
m_RowIndex = i_RowIndex;
m_ColIndex = i_ColIndex;
m_Coin = i_CoinType;
}
调用new
将创建另一个将被垃圾收集的实例,因为您不存储对它的引用。 此外,原始实例中的m_Coin将不会被设置(或者更确切地说将被设置为default(eCointType)
。
public Square( int i_RowIndex, eColumn i_ColIndex) : this(i_RowIndex, i_ColIndex, eCoinType.NoCoin)
{
}
public Square(int i_RowIndex, eColumn i_ColIndex, eCoinType i_CoinType)
{
m_RowIndex = i_RowIndex;
m_ColIndex = i_ColIndex;
m_Coin = i_CoinType;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.