访问存储为列表中项目的类的属性/字段

时间:2018-12-30 05:23:29

标签: c#

我正在尝试从main访问类stationName & stationId中的字段Station,但无法访问。 有这个原因吗?

public class Station : Line
{
    public string stationName;
    public string stationId;
}

public class Line
{
    public List<Station> line = new List<Station>();
}

class Function
{
    static void Main(string[] argv)
    {
        using (StreamReader reader = new StreamReader(argv[0]))
        {
            string temp;
            Line line = new Line();

            while ((temp = reader.ReadLine()) != null)
            {
               // error here
               line.line.stationName = line;
            }
        }
    }
}

我最终将字段设为属性,但这不会改变问题。

3 个答案:

答案 0 :(得分:2)

问题在这一行

line.line.stationName

line是一个列表。您需要使用索引来访问它。例如,要获取stationame

line.line[index].stationName

在您的情况下,您要将Station的实例添加到行中。因此,您需要

    using (StreamReader reader = new StreamReader(argv[0]))
    {
        string temp;
        Line line = new Line();
        while ((temp = reader.ReadLine()) != null)
        {
           line.line.Add(new Station
           {
             stationName = "value you want to assign"
           });

        }
    }

答案 1 :(得分:0)

您没有在List<Station>中添加项目。您将需要在循环中创建Station对象,并将其添加到line类内的Line集合中。

您需要写:

Line line = new Line();

while ((temp = reader.ReadLine()) != null)
{
    Station s = new Station();
    s.stationName = "stationName";

    line.line.Add(s);
}

最好使用变量的好名称。您可以将其重命名为Stations

public class Line
{
    public List<Station> Stations = new List<Station>();
}

使您的代码更易于阅读:

while ((temp = reader.ReadLine()) != null)
{
    Station station = new Station();
    station.stationName = "stationName";

    line.Stations.Add(station);
}

答案 2 :(得分:0)

您的完整程序应该更精确地是这样,

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Station
    {
        public string stationName;
        public string stationId;
    }

    public class Line
    {
        public List<Station> stations = new List<Station>();
    }

    class Program
    {
        static void Main(string[] argv)
        {
            using (StreamReader reader = new StreamReader(argv[0]))
            {
                string temp;
                Line line = new Line();
                int i = 0;

                while ((temp = reader.ReadLine()) != null)
                {
                    line.stations.Add(new Station
                    {
                        stationName = temp,
                        stationId = (++i).ToString()
                    });
                }

                //For printing
                foreach (var station in line.stations)
                {
                    Console.WriteLine(station.stationName);
                    Console.WriteLine(station.stationId);
                }

                Console.ReadLine();
            }
        }
    }
}