我创建了一个列表,可以存储文本文件中的所有输入值。现在我需要从另一个类访问此列表。代码是否需要进行任何更改?
public static void boxdetails()
{
String line;
List<Box> listofboxes = new List<Box>();
try
{
using (StreamReader sr = new StreamReader("c:/boxvalues.txt"))
while ((line = sr.ReadLine()) != null)
{
// create new instance of container for each line in file
Box box = new Box();
// List<Box> listofboxes = new List<Box>();
string[] Parts = line.Split(' ');
// set non-static properties of container
box.bno = Parts[0];
box.length = Convert.ToDouble(Parts[1]);
box.height = Convert.ToDouble(Parts[2]);
box.depth = Convert.ToDouble(Parts[3]);
box.volume = Convert.ToDouble(Parts[4]);
box.placed = Convert.ToBoolean(Parts[5]);
// add container to list of containers
}
listofboxes.Add(box);
Console.WriteLine((box.bno) + "is ADDED");
listofboxes = listofboxes.OrderBy(x => x.volume).ToList();
}
//[code incomplete]
答案 0 :(得分:1)
第1步:使用List<Box>
访问修饰符声明方法外的public
。
class ClassA
{
public List<Box> myList = new List<Box>();
}
第2步:使用该类的实例变量从任何其他类访问List<Box>
。
class ClassB
{
ClassA aRef=new ClassB();
aRef.myList.Add(myBox);//access here
}
答案 1 :(得分:0)
尝试将listofboxes
设为会员财产,如下所示:
public List<Box> ListOfBoxes
{
get
{
return this._listOfBoxes;
}
set
{
this._listOfBoxes = value;
}
}
private List<Box> _listOfBoxes = new List<Box>();
然后改变你的代码:
while ((line = sr.ReadLine()) != null)
{
// create new instance of container for each line in file
Box box = new Box();
// List<Box> listofboxes = new List<Box>();
string[] Parts = line.Split(' ');
// set non-static properties of container
box.bno = Parts[0];
box.length = Convert.ToDouble(Parts[1]);
box.height = Convert.ToDouble(Parts[2]);
box.depth = Convert.ToDouble(Parts[3]);
box.volume = Convert.ToDouble(Parts[4]);
box.placed = Convert.ToBoolean(Parts[5]);
// add container to list of containers
this.ListOfBoxes.Add(box);
}
答案 2 :(得分:0)
将列表声明为静态,以便您可以使用类名
从任何类访问等
ClassName.listofboxes //assign to some other list or use as per ur need
.....
public static List<Box> listofboxes;
public static void boxdetails()
{
listofboxes = new List<Box>();
...
}