如何从.txt文件传递数据并在继承的类中单独构造它们

时间:2016-01-02 16:33:08

标签: c# inheritance

我创建了一个继承的类,并将数据放在与父类相同的.txt文件中。我需要帮助将对象从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;
    }

}

提前感谢您的帮助

2 个答案:

答案 0 :(得分:1)

你可以尝试以下......

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();

答案 1 :(得分:0)

我会使用工厂类来解析和创建类型为promotion的对象。 该方法使用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();
    }