c#函数和类有帮助
本文关键字:有帮助 函数 | 更新日期: 2023-09-27 17:50:19
说我有
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());
真的在temp类中将temp3添加到列表中吗?
No.
行应该是:
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());
。你应该像这样使用get方法getAList()
t.getAList.Add(new temp3());
下面的代码做你想做的
使用系统;使用System.Collections.Generic;使用来;使用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());
}
}
}