将数据从文本文件传递到构造函数

Passing Data From Text File to Constructor

我正在寻找一种将信息从文本文件传递到构造函数的方法,以便我可以创建该构造函数对象的数组,数组中的每个对象都保存来自文本文件行的信息。

构造函数格式如下:

public Member(string name, int number, decimal rate, double hours)

虽然文本文件的格式是这样的:

Eric Wallace,    352456, 15.88, 32.20
Clara Kell,     233424, 35.88, 18.76
Darren Price,   656795, 27.82, 20.25
etc...

每个成员都会进入一个数组。

最后,我需要的是将每一行拆分并传递给构造函数,使每一行成为数组中的自己的成员,以便它们可以在循环中一个接一个地输出或作为行单独调用。

我的方法将从创建一个接口开始,我的所有“可构建”数据类型都将实现该接口。我希望我的数据模型决定它们是如何从字符串构建的:

    public interface IBuildableFromString
    {
        public IBuildableFromString Build(string str, string seperator = ",");
    }

然后让Member像这样实现它:

    public class Member : IBuildableFromString
    {
        public string Name { get; set; }
        public int Number { get; set; }
        public decimal Rate { get; set; }
        public double Hours { get; set; }

        public Member() { }
        public Member(string name, int number, decimal rate, double hours)
        {
            Name = name;
            Number = number;
            Rate = rate;
            Hours = hours;
        }

        public IBuildableFromString Build(string str, string seperator = ",")
        {
            try
            {
                string[] parts = str.Split(seperator);
                return new Member(parts[0], int.Parse(parts[1]), 
                    decimal.Parse(parts[2]), double.Parse(parts[3]));
            }
            catch
            {
                return null;
            }
        }
    }

然后是读取文件构建对象数据的方法:

        public static T[] BuildData<T>(string filePath) where T : 
                                                        IBuildableFromString, new()
        {
            List<T> dataObjects = new List<T>();
            string[] lines = File.ReadAllLines(filePath);

            foreach (string line in lines)
            {
                if (!String.IsNullOrEmpty(line))
                {
                    var newMember = new T().Build(line);
                    if (newMember != null)
                        dataObjects.Add((T)newMember);
                }
            }

            return dataObjects.ToArray();
        }

最后,像这样调用上面的函数:

        static void Main(string[] args)
        {
            var data = BuildData<Member>(@"path_to_your_file.txt");
        }

它可能需要更多的错误检查,但这是我能想到的最可扩展的方式。干杯!

只要您的文件格式正确,就可以:

Member[] members =
    File
        .ReadLines(@"mytextfile.txt")
        .Select(x => x.Split(',').Select(y => y.Trim()).ToArray())
        .Select(x => new Member(x[0], int.Parse(x[1]), decimal.Parse(x[2]), double.Parse(x[3])))
        .ToArray();

我会用StreamReader读取txt文件,然后用replace消除空格,再用split拆分数据

Use StreamReader to read text from a file:

StreamReader sr = new StreamReader(@"C:\demo\de.txt")

让会员像这样实现它:

public class Member {
            public string Name { get; set; }
            public int Number { get; set; }
            public decimal Rate { get; set; }
            public double Hours { get; set; }
            public Member(string name, int number, decimal rate, double hours) {
                Name = name;
                Number = number;
                Rate = rate;
                Hours = hours;
            }
        }

这样调用数据:

foreach (var item in members) {
                Console.WriteLine($"{ item.Name}  { item.Number}  { item.Rate}   { item.Hours}");
            }

总码数:

using System;
using System.Collections.Generic;
using System.IO;

namespace ConsoleApp2 {
    class Program {
        static void Main(string[] args) {
            List<Member> members = new List<Member>();  
            try {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader(@"C:\demo\de.txt")) {
                    string line;
                    // Read and display lines from the file until the end of
                    // the file is reached.
                    while ((line = sr.ReadLine()) != null) {
                        line = line.Replace(" ", "");
                        string[] tmp = line.Split(',');
                        string name = tmp[0];
                        int number = Convert.ToInt32(tmp[1]);
                        decimal rate = Convert.ToDecimal(tmp[2]);
                        double hours = Convert.ToDouble(tmp[3]);
                        members.Add(new Member(name, number, rate, hours));                    
                    }
                }
            } catch (Exception e) {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
            foreach (var item in members) {
                Console.WriteLine($"{ item.Name}  { item.Number}  { item.Rate}   { item.Hours}");
            }

            Console.ReadLine();
        }

        public class Member {
            public string Name { get; set; }
            public int Number { get; set; }
            public decimal Rate { get; set; }
            public double Hours { get; set; }
            public Member(string name, int number, decimal rate, double hours) {
                Name = name;
                Number = number;
                Rate = rate;
                Hours = hours;
            }
        }
    }
}

如有疑问,欢迎留言。