如何从.txt文件传入数据,并在继承的类中分别构造它们

本文关键字:继承 文件 txt 数据 | 更新日期: 2023-09-27 18:28:40

我创建了一个继承的类,并将数据放在与父类相同的.txt文件中。我需要帮助将对象从txt文件构造到继承的类中。这是文本文件

1101,Lemon Tea,2.00
1102,Green Tea,1.90
1103,Black Tea,2.50
1104,Milo,1.50
1201,Coca Cola,2.00
1202,Pepsi,2.00
1203,Whatever,2.10 
1204,Anything,2.10
2101,Unadon,8.50
2102,Tamagodon,7.50
2103,katsudon,8.10
2104,Oyakodon,7.80
2105,Ikuradon,8.00
2201,onigiri,10.00
2202,maki,9.50
2203,aburi sushi,6.50
2204,temari sushi,4.50
2205,oshi sushi,7.50
2301,kaarage,9.20
2302,gyuniku,9.50
2303,tempura,9.00
2304,unagi,8.00
5501,Bento Of the Year(kaarage bento),4.60,2017,1,1
5502,Winter Promotion(2x sake bento + 2x Ice Lemon Tea),25.00,2016,31,1
5503,Sushi Galore(all sushi For $30.00),30.00,2017,1,1
5504,New Year Special(4x bento + 4x Green Tea),35.00,2016,15,15

这是我的继承类

class Promotion : product
{
    private DateTime dateEnd;
    public Promotion(int sn, string n, double p, DateTime dt) : base(sn, n, p) 
    {
        dateEnd = dt;
    }
    public Promotion(DateTime dt)
    {
        dateEnd = dt;
    }
    public DateTime PromoType
    {
        get { return dateEnd; }
        set { dateEnd = value; }
    }
    public string getPromoInfo()
    {
        string info = base.product_info();
        info +=  dateEnd;
        return info;
    }
}

提前感谢您的帮助

如何从.txt文件传入数据,并在继承的类中分别构造它们

您可以尝试以下操作。。。

string line;
List<product> promotions = new List<product>();
// Read the file and display it line by line.
System.IO.StreamReader file = 
    new System.IO.StreamReader(@"c:'yourFile.txt");
while((line = file.ReadLine()) != null)
{
    string[] words = line.Split(',');
    if(words.length == 4)
    {
        promotions.Add(new Promotion(words[0],words[1],words[2],words[3]));
    }
    else
    {
        promotions.Add(new product(words[0],words[1],words[2]));
    }
}
file.Close();

我会使用一个工厂类来解析和创建类型提升的对象。该方法使用yield return语句逐行读取和处理文件。作为一种替代方法,您也可以一次读取文件内容。

工厂类别:

public class PromotionFactory : IPromotionFactory
{
    public IEnumerable<IPromotion> Parse(string file)
    {
        if (string.IsNullOrEmpty(file)) throw new ArgumentException(nameof(file));
        var result = new List<IPromotion>();
        foreach (var line in ReadFile(file))
        {
            var promotion = ParseLine(line);
            result.Add(promotion);
        }
        return result;
    }
    private IPromotion ParseLine(string line)
    {
        var segments = line.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
        if (segments.Length == 0) throw new ArgumentException("Could not read segments");
        var id = int.Parse(segments[0]);
        var name = segments[1];
        var price = decimal.Parse(segments[2]);
        DateTime? date = null;
        if (segments.Length > 3)
        {
            date = new DateTime(int.Parse(segments[3]), int.Parse(segments[5]), int.Parse(segments[4]));
        }
        return new Promotion(id, name, price, date);
    }
    private IEnumerable<string> ReadFile(string file)
    {
        string line;
        using (var reader = File.OpenText(file))
        {
            while ((line = reader.ReadLine()) != null)
            {
                if (!string.IsNullOrWhiteSpace(line))
                {
                    yield return line;
                }
            }
        }
    }
}

推广班:

public class Promotion : Product, IPromotion
{
    public Promotion(int id, string name, decimal price, DateTime? date) : base (id, name, price)
    {
        Date = date;
    }
    public DateTime? Date { get; }
    public override string ToString()
    {
        var builder = new StringBuilder();
        builder.AppendLine("Promotion:");
        builder.AppendLine($"Id: {Id}");
        builder.AppendLine($"Name: {Name}");
        builder.AppendLine($"Price: {Price}");
        builder.AppendLine(string.Format("Date: {0}", Date != null ? Date.Value.ToString("yyyy-MM-dd") : string.Empty));
        return builder.ToString();
    }
}

调用类

 public static void Main(string[] args)
    {
        var file = string.Format("{0}//foobar.txt", Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
        var factory = new PromotionFactory();
        var promotions = factory.Parse(file);
        promotions.ToList().ForEach(Console.WriteLine);
        Console.ReadKey();
    }