[英]ToString override to return array
我想制作一个 wpf 程序,当您单击“生成”按钮时,SSales 类将获取/存储该类的值数组,然后将其返回到列表框。 新来的。 对不起。
private void GenerateButton_Click(object sender, EventArgs e)
{
Random rand = new Random();
int[] year = { 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 };
double[] Sales = new double[10];
for (int i = 0; i < 10; i++)
{
Sales[i] = rand.Next(1000, 50000);
}
SSales yearSale = new SSales(year, Sales);
for (int j = 0; j < 10; j++){
//I want the listbox to display the values of yearSale.Year and yearSale.Sales
listBox1.Items.Add(yearSale);
}
}
public class SSales
{
public int[] Year { get; set; }
public double[] Sales { get; set; }
public SSales(int[] iYear, double[] dSales)
{
Year = iYear;
Sales = dSales;
}
public override string ToString()
{
//I'm trying to make this format "2001 $25,000.00" then return it to listbox
return string.Format("{0}\t\t{1:C0}", Year, Sales);
}
}
由于您SSales
ListBox
添加 10 个SSales
对象,因此每个对象都应接受一个int
和一个double
:
public class SSales
{
public int Year { get; set; }
public double Sales { get; set; }
public SSales(int iYear, double dSales)
{
Year = iYear;
Sales = dSales;
}
public override string ToString()
{
return string.Format("{0}\t\t{1:C0}", Year, Sales);
}
}
尝试这个:
private void GenerateButton_Click(object sender, EventArgs e)
{
Random rand = new Random();
int[] year = { 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 };
double[] Sales = new double[10];
for (int i = 0; i < 10; i++)
{
Sales[i] = rand.Next(1000, 50000);
}
for (int j = 0; j < 10; j++)
{
listBox1.Items.Add(new SSales(year[j], Sales[j]));
}
}
这不是你使用 ToString 的方式——它不应该返回一个数组。
相反,您应该在 SSales 上创建一个带有参数的函数,这将为您提供所需的销售的格式化结果。 像这样的东西:
public string GetFormattedSale(int s) { string.Format("{0}\\t\\t{1:C0}", Year[s] , Sales[s]);
}
然后,您可以像这样从按钮单击代码中调用它:
listBox1.Items.Add(yearSale.GetFirmattedSale(j));
如果您确实必须使用 ToString,则需要创建另一个类,其中包含单个销售的数据,而不是所有 10 个销售的数据。 然后,您可以仅针对该单次销售实施 ToString。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.