【问题标题】:How to pass filled list to another class?如何将填写好的列表传递给另一个班级?
【发布时间】:2019-06-07 10:00:09
【问题描述】:

我创建了一个包含 x,y 的点结构。我还创建了一个类来向列表中添加点。我正在尝试解析 Reader Class 中的 XML 文件,并使用该 XML 文件中的点填充列表。之后,我尝试使用我在 Reader 类中解析的点在“Writer 类”中创建另一种数据格式。代码示例只是示例,但我想做的是相同的。

通常使用 button1 它必须是读取点并用它们填充列表,使用 button2 它必须创建另一种数据格式。但它不起作用。我错过了什么?

点结构:

public struct Point2D 
{
        #region Constructors
        public Point2D(double x, double y)
        {
            this.X = x;
            this.Y = y;
        }
        #endregion Constructors
        public readonly double X;   
        public readonly double Y;
}

集合类:

public class List 
{
    public List<Point2D> points { get; }

    public List()
    {
        this.points = new List<Point2D>();
    }

    public void AddPoint(Point2D p)
    {
        this.points.Add(p);
    }
}

读者:

public class Reader
{
    public static void Read()
    {
        double X = 1.5;
        double Y = 2.5;

        var list = new List();

        list.AddPoint(new Point2D(X, Y));  
    }
}

作者:

public static class Writer
{
    public static void GetPoints(List list)
    {
        var X = list.points[0].X.ToString();
        StreamWriter sr = new StreamWriter(@"...\test.txt");
        sr.WriteLine(X);
    }
}

应用:

public partial class Form1 : Form
{
    public List List { get; private set; }
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Reader.Read();
    }
    private void button2_Click(object sender, EventArgs e)
    {
        Writer.GetPoints(this.List);
    }
}

【问题讨论】:

    标签: c# oop properties


    【解决方案1】:

    我可以看到 Form1List 属性未分配。这样 Writer.GetPoints(this.List); 失败。

    reader.Read() 时可以返回列表,并用 Form1 的 List 属性赋值,如下所示。

    private void button1_Click(object sender, EventArgs e)
    {
        this.List= Reader.Read();
    }
    

    读取方法应更改如下。

    public class Reader
    {
        public static List Read()
        {
            double X = 1.5;
            double Y = 2.5;
    
            var list = new List();
    
            list.AddPoint(new Point2D(X, Y));
            return list;
        }
    }
    

    【讨论】:

    • 嗨迪帕克。它运作良好!谢谢你的时间和教训:)
    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多