我一直在使用C++和c#中的new。在C++中,我使用int a[8]
來聲明一個數組,如果數組是一個對象,我們設置的值爲item[0].SetID(5)
,它將設置第一項ID的值爲5.但我無法在c#中完成。如何在陣列中使用Getter setter
namespace Arrays
{
class items {
public int ID { set; get; }
public string name { set; get; }
public items(int ID) {
this.ID = ID;
name = "Faizan";
}
}
class Program
{
static void Main(string[] args)
{
var i=new items[4];
i[0].ID=6;// this line is kind of c++ code but how I do it in c#
Random r = new Random();
for (int k = 0; k < 4; k++) {
i[k] = new items(r.Next());
}
foreach(items it in i){
Console.WriteLine("The item name {0} and the Id is {1}",it.name,it.ID);
}
}
}
}
你的數組將充滿空元素。您需要在int [0] –
中實例化對象與您的問題無關的建議:您可以考慮調用您的類「item」而不是「items」。這樣做會更好,因爲課堂似乎是模擬單個項目而不是項目集合。一個小問題,但它會讓你的代碼更加可讀性,任何人都不熟悉它。 – razlebe