[英]C# functions and classes help
說我有
class temp {
private List<temp3> aList = new List<temp3>();
public List<temp3> getAList()
{
return this.aList;
}
public temp() {
}
}
class temp3 {
public temp3() {}
}
現在我有另一堂課
class temp2 {
private temp t = new temp();
t.aList.Add(new temp3());
}
將
t.getAList.Add(new temp3());
真的將temp3添加到temp類的aList中?
沒有。
該行應為:
t.getAList().Add(new temp3());
閱讀評論后進行編輯 :將該行放入方法中。
temp.aList
是私有的,所以那是行不通的。 您想要做的是向temp
類添加一個屬性:
public List<temp3> AList
{
get {return aList;}
set {aList = value;}
}
然后將其用作t.AList.Add(new temp3())
正如Akram Shahda在注釋中指出的那樣,您必須在類中為其創建一個方法。 您不能在類中直接使用此類語句。
aList
是私有的,您無法通過t.aList.Add(new temp3());
到達t.aList.Add(new temp3());
。 您應該像這樣使用get方法getAList()
t.getAList.Add(new temp3());
下面的代碼做你想做的
使用系統; 使用System.Collections.Generic; 使用System.Linq; 使用System.Text;
namespace Project4
{
class temp {
private List<temp3> aList = new List<temp3>();
public List<temp3> getAList
{
get{return aList;}
set{aList = value;}
}
public temp() {
}
}
class temp3 {
public temp3() {}
}
class temp2 {
public static void Method()
{
temp t = new temp();
t.getAList.Add(new temp3());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.