输入:任何指定日期的所有销售数据,通过以下代码从字符串中提取:
class Program
{
static void Main(string[] args)
{
List<Sale> Sales = new List<Sale>();
// int l = 1;
using (StreamReader reader = new StreamReader("file.dat"))
{
string line;
var locations = new Dictionary<string, int[]>() {
{"210", new [] {405, 4, 128, 12, 141, 12, 247, 15, 121, 3}},
{"310", new [] {321, 4, 112, 12, 125, 12, 230, 15, 105, 3}},
{"410", new [] {477, 4, 112, 12, 125, 12, 360, 15, 105, 3}}
};
while ((line = reader.ReadLine()) != null)
{
var lineStart = line.Substring(0, 3);
if (lineStart == "210" || lineStart == "310" || lineStart == "410")
{
var currentLocations = locations[lineStart];
var letters = line.Substring(currentLocations[0], currentLocations[1]);
var volume =
int.Parse(line.Substring(currentLocations[2], currentLocations[3])) +
int.Parse(line.Substring(currentLocations[4], currentLocations[5]));
var price = long.Parse(line.Substring(currentLocations[6], currentLocations[7]));
var mvolume = price * volume;
var currency = line.Substring(currentLocations[8], currentLocations[9]);
这会从字符串中获取所需的信息。
我有一个单独的类,其字段与这些变量相同,但名称略有不同。
public class Sale
{
private int CashTotal;
private string codeletters;
private string Crncy;
}
我的主要代码中还有:
Sale s = new Sale();
Sales.Add(s);
(这是我到目前为止的完整代码,只是分成几部分,它在程序中从上到下读取 - 除了新类)。
此时我正在努力做的是将每个var中的值加载到类中的字段中(将Currency作为Crncy存储,mvolume作为totalcash,将字母作为codeletters),存储该对象(Sale )进入列表(Sales),然后再次重复。我很确定这是一个非常基本的解决方案,但如果我能想到它,我就会被塞满。
编辑:对不起,解决了那个,然后编辑了代码,相应地,我会告诉你我尝试过哪些不起作用,但应该传达我想要做的事情的逻辑:
Sale.CashTotal = mvolume;
Sale.Crncy = currency;
Sale.codeletters = letters;
我已将字符串分解为其组成部分,但我只能在列表中存储一个对象,因此我需要将它们重新组合为Sale,并将其存储在列表中,但将这些值存入销售证明是有问题的。
答案 0 :(得分:1)
您已将字段声明为private
,因此无法在课程外访问它们。您可以声明一个公共构造函数并在那里传递值。您还可以添加仅包含get
个访问者的publiv属性:
public class Sale
{
private int totalCash;
public int TotalCash
{
get { return totalCash; }
}
private string codeletters;
public string Codeletters
{
get { return codeletters; }
}
private string crncy;
public string Crncy
{
get { return crncy; }
}
public Trade(int _totalCash, string _codeletters, string _crncy)
{
totalCash = _totalCash;
codeletters = _codeletters;
crncy = _crncy;
}
}
然后将使用:
Sale s = new Sale(mvolume,letters,currency);
或者你可以让他们public
:
public int TotalCash;
public string codeletters;
public string Crncy;
然而,公共字段的定义很糟糕,所以你最好把它们设为自动属性:
public int TotalCash {get; set;}
public string CodeLetters {get; set;}
public string Crncy {get; set;}
请阅读MSDN以获取更多信息:Access Modifiers