由于字符串解析问题而覆盖类对象

本文关键字:覆盖 对象 问题 字符串 | 更新日期: 2023-09-27 18:31:19

我正在尝试读取一个固定宽度的文本文件并将每个元素存储到类对象中。 需要检查文本文件中的每一行,以确定必须执行哪个解析操作。 第 1000 行和第 1001 行都需要以不同的方式进行分析,第 1002-1004 行使用相同的解析操作。 我正在读取文件并正确解析,但是当我向类对象添加元素时,每个"if"语句中的对象都会被覆盖。 然后,当对象添加到列表中时,列表包含空行。 我觉得我采取了错误的方法。 我是 C# 的新手,如果已经回答了这个问题,我深表歉意,但经过几个小时的搜索,我找不到解决方案。 下面是文本文件和代码。

1000 属性一 属性二
1001 123456.000000 属性四
1002 1234.0 2345.0 3456.01003 1234.0 2345.0 3456.01004 1234.0 2345.0 3456.01000 属性一 属性二
1001 456789.000000 属性四
1002 1234.0 2345.0 3456.01003 1234.0 2345.0 3456.01004 1234.0 2345.0 3456.01000 属性一 属性二
1001 234567.000000 属性四
1002 1234.0 2345.0 3456.01003 1234.0 2345.0 3456.01004 1234.0 2345.0 3456.01000 属性一 属性二
1001 345678.000000 属性四
1002 1234.0 2345.0 3456.01003 1234.0 2345.0 3456.01004 1234.0 2345.0 3456.0

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
namespace list_question
{    
    public class someObject
    {
        //Line 1
        public int Line1_ID;
        public string Line1_Attribute1;
        public string Line1_Attribute2;
        //Line 2
        public int Line2_ID;
        public decimal Line2_Attribute3;
        public string Line2_Attribute4;
        //Line 3
        public int Line3_ID;
        public decimal data_pos1;
        public decimal data_pos2;
        public decimal data_pos3;        
    }
    class Program
    {
        static void Main(string[] args)
        {
            string filepathRead = @"C:'Users'user1'Desktop'SampleFile.txt";
            List<someObject> somObList = new List<someObject>();
            try
            {
                FileStream fs = new FileStream(filepathRead, FileMode.Open, FileAccess.Read);
                StreamReader reader = new StreamReader(fs);                               
                while (!reader.EndOfStream) 
                {                         
                    string line = reader.ReadLine();
                    if ((line.Substring(0, 4) == "1000"))
                    {
                        string[] strArrFields1 = Regex.Split(line, @"(.{6})" + "(.{14})" + "(.{20})").Where(s => !string.IsNullOrEmpty(s)).ToArray();
                        someObject obj_1 = new someObject();                        
                        obj_1.Line1_ID = int.Parse(strArrFields1[0].TrimEnd(' '));
                        obj_1.Line1_Attribute1 = strArrFields1[1].TrimEnd(' ');
                        obj_1.Line1_Attribute2 = strArrFields1[2].TrimEnd(' ');
                        somObList.Add(obj_1);
                    }
                    else if ((line.Substring(0, 4) == "1001"))
                    {
                        string[] strArrFields2 = Regex.Split(line, @"(.{6})" + "(.{20})" + "(.{15})").Where(s => !string.IsNullOrEmpty(s)).ToArray();                        
                        someObject obj_1 = new someObject();
                        obj_1.Line2_ID = int.Parse(strArrFields2[0].TrimEnd(' '));
                        obj_1.Line2_Attribute3 = decimal.Parse(strArrFields2[1].TrimEnd(' '));
                        obj_1.Line2_Attribute4 = strArrFields2[2].TrimEnd(' ');
                        somObList.Add(obj_1);
                    }
                    else
                    {
                        string[] strArrFields3 = Regex.Split(line, @"(.{6})" + "(.{7})" + "(.{7})" + "(.{7})").Where(s => !string.IsNullOrEmpty(s)).ToArray();                        
                        someObject obj_1 = new someObject();
                        obj_1.Line3_ID = int.Parse(strArrFields3[0].TrimEnd(' '));
                        obj_1.data_pos1 = decimal.Parse(strArrFields3[1].TrimEnd(' '));
                        obj_1.data_pos2 = decimal.Parse(strArrFields3[2].TrimEnd(' '));
                        obj_1.data_pos3 = decimal.Parse(strArrFields3[3].TrimEnd(' '));                        
                        somObList.Add(obj_1);
                    }  
                } 
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Program Exited");
                Environment.Exit(99);
            }             
            foreach (someObject o in somObList)
            {
                Console.WriteLine("{0},{1},{2}'n{3},{4},{5}'n{6},{7},{8},{9}",
                    o.Line1_ID, o.Line1_Attribute1, o.Line1_Attribute2, o.Line2_ID, o.Line2_Attribute3, o.Line2_Attribute4, o.Line3_ID, o.data_pos1, o.data_pos2, o.data_pos3);
            }
            somObList.Clear();
        }
    }
}

由于字符串解析问题而覆盖类对象

首先,您的数据文件是这样的吗?

1000 AttributeOne AttributeTwo
1001 123456.000000 AttributeFour
1002 1234.0 2345.0 3456.0 
1003 1234.0 2345.0 3456.0 
1004 1234.0 2345.0 3456.0 
1000 AttributeOne AttributeTwo  
1001 456789.000000 AttributeFour
1002 1234.0 2345.0 3456.0 
1003 1234.0 2345.0 3456.0 
1004 1234.0 2345.0 3456.0 
1000 AttributeOne AttributeTwo
1001 234567.000000 AttributeFour
1002 1234.0 2345.0 3456.0 
1003 1234.0 2345.0 3456.0 
1004 1234.0 2345.0 3456.0 
1000 AttributeOne AttributeTwo
1001 345678.000000 AttributeFour
1002 1234.0 2345.0 3456.0 
1003 1234.0 2345.0 3456.0 
1004 1234.0 2345.0 3456.0

其次,为什么要使用正则表达式来拆分文本?如果您担心间距,为什么不将其规范化。

接下来,您将在每个 if 语句中覆盖您的对象。

这是我对您的代码的修订版本。

using System;
using System.Linq;
using System.Data;
using System.Data.Linq;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace OverwritingClassObjectHelp
{
    public class someObject
    {
        //Line 1
        public int Line1_ID;
        public string Line1_Attribute1;
        public string Line1_Attribute2;
        //Line 2
        public int Line2_ID;
        public decimal Line2_Attribute3;
        public string Line2_Attribute4;
        //Line 3
        public int Line3_ID;
        public decimal data_pos1;
        public decimal data_pos2;
        public decimal data_pos3;  
        //Line 4
        public int Line4_ID;
        public decimal data_pos4;
        public decimal data_pos5;
        public decimal data_pos6; 
    }
    class MainClass
    {
        public static void Main (string[] args)
        {
            string filepathRead = @"C:'Users'C121736'Desktop'SampleFile.txt";
            List<someObject> somObList = new List<someObject>();
            try
            {
                FileStream fs = new FileStream(filepathRead, FileMode.Open, FileAccess.Read);
                StreamReader reader = new StreamReader(fs);
                someObject obj_1 = null;
                while (!reader.EndOfStream) 
                {                         
                    string line = reader.ReadLine();

                    if(String.IsNullOrWhiteSpace(line))
                    {
                        // if line is empty do nothing
                        continue;
                    }
                    else if ((line.Substring(0, 4) == "1000"))
                    {
                        // normalize
                        line = Regex.Replace(line, @"'s+", " ");
                        string[] strArrFields = line.Split();
                        obj_1 = new someObject();                        
                        obj_1.Line1_ID = int.Parse(strArrFields[0]);
                        obj_1.Line1_Attribute1 = strArrFields[1];
                        obj_1.Line1_Attribute2 = strArrFields[2];
                    }
                    else if ((line.Substring(0, 4) == "1001"))
                    {
                        if(obj_1 == null) continue;
                        // normalize
                        line = Regex.Replace(line, @"'s+", " ");
                        string[] strArrFields = line.Split();

                        obj_1.Line2_ID = int.Parse(strArrFields[0]);
                        obj_1.Line2_Attribute3 = decimal.Parse(strArrFields[1]);
                        obj_1.Line2_Attribute4 = strArrFields[2];
                        somObList.Add(obj_1);
                    }
                    else if(line.Substring(0, 4) == "1003") 
                    {
                        if(obj_1 == null) continue;
                        // normalize
                        line = Regex.Replace(line, @"'s+", " ");
                        string[] strArrFields = line.Split();
                        obj_1.Line3_ID = int.Parse(strArrFields[0]);
                        obj_1.data_pos1 = decimal.Parse(strArrFields[1]);
                        obj_1.data_pos2 = decimal.Parse(strArrFields[2]);
                        obj_1.data_pos3 = decimal.Parse(strArrFields[3]);
                    }
                    else if(line.Substring(0, 4) == "1004")
                    {
                        if(obj_1 == null) continue;
                        // normalize
                        line = Regex.Replace(line, @"'s+", " ");
                        string[] strArrFields = line.Split();

                        obj_1.Line4_ID = int.Parse(strArrFields[0]);
                        obj_1.data_pos4 = decimal.Parse(strArrFields[1]);
                        obj_1.data_pos5 = decimal.Parse(strArrFields[2]);
                        obj_1.data_pos6 = decimal.Parse(strArrFields[3]);
                        somObList.Add(obj_1);
                        obj_1 = null;
                    }
                } 
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Program Exited");
                Environment.Exit(99);
            }             
            foreach (someObject o in somObList)
            {
                Console.WriteLine("{0},{1},{2}'n{3},{4},{5}'n{6},{7},{8},{9}",
                                  o.Line1_ID, o.Line1_Attribute1, o.Line1_Attribute2, o.Line2_ID, o.Line2_Attribute3, o.Line2_Attribute4, o.Line3_ID, o.data_pos1, o.data_pos2, o.data_pos3);
            }
            somObList.Clear();
        }
    }
}

你来了。这并不完全适用于您任务的细节,但我希望引导您朝着适当的方向前进。我自己仍然是一个新开发人员..但也许你会从这种略有不同的方法中受益。首先,将对象分离到一个新的类文件中。这是我的,叫Item.cs

    public class Item
    {
        public string Attribute1 { get; set; }
        public string Attribute2 { get; set; }
    }

这是程序。就像我说的,这对你来说不是即插即用的,但如果你注意到我是如何完成你的任务的,你甚至可以进一步完善它。我只是使用一个基本的文本文件进行快速测试。让我知道它是如何为你工作的。

    static void Main(string[] args)
    {
        List<Item> myItems = new List<Item>();
        List<string> myFile = File.ReadAllLines("C:''Path''Values.txt").ToList();
        foreach (string value in myFile)
        {
            switch(value.Substring(0,4))
            {
                case "1001":
                    myItems.Add(MyParseMethod1(value));
                    break;
                case "1002":
                    myItems.Add(MyParseMethod2(value));
                    break;
                default:
                    myItems.Add(MyDefaultParser(value));
                    break;
            }
        }
    }
    public static Item MyParseMethod1(string stringIWishtoParse)
    {
        Item myItem = new Item();
        //Parse string, set object values
        //myItem.Attribute1 = whatever portion you want from your string
        return myItem;
    }
    public static Item MyParseMethod2(string stringIWishtoParse)
    {
        Item myItem = new Item();
        //Parse string, set object values
        //myItem.Attribute1 = whatever portion you want from your string
        return myItem;
    }
    public static Item MyDefaultParser(string stringIWishtoParse)
    {
        //Follow pattern from other methods
    }
}