在下面的代碼塊中,爲什麼我需要在類中聲明myData,然後在構造函數中初始化myData = new string [size]?爲什麼編寫私有字符串[] myData = new string [size]是非法的?C#構造函數幫助
也就是說,爲什麼我需要做的:
class IntIndexer
{
private string[] myData;
public IntIndexer(int size)
{
myData = new string[size];
for (int i = 0; i < size; i++)
{
myData[i] = "empty";
}
}
}
而不是
class IntIndexer
{
private string[] myData = new string[size];
public IntIndexer(int size)
{
for (int i = 0; i < size; i++)
{
myData[i] = "empty";
}
}
}
你能澄清這個問題嗎?你在問爲什麼成員變量必須在函數範圍之外聲明,或者你發現你的構造函數沒有按預期工作? – 2009-08-01 15:47:52