[英]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.