我正在尝试打印名为Transactions的通用链接列表的内容,但输出是“Task3.Transaction”。通用链表将Transaction类作为其数据类型,因为我使用Transaction类在链表中创建节点。
这是我的代码:
我的代码中出现问题的部分在其两侧都有* *。
private void button1_Click(object sender, EventArgs e)
{
LinkedList<Transaction> Transactions = new LinkedList<Transaction>(); //create the generic linked list
SqlConnection con = new SqlConnection(@"Data Source=melss002; Initial Catalog=30001622; Integrated Security=True"); //Connection string
int accNum = Int32.Parse(Microsoft.VisualBasic.Interaction.InputBox("Please enter account number", "Account Number")); //Prompt the user for account number
SqlCommand cmd = new SqlCommand("Select * From Transactions where AccountNo = " + accNum, con); //command to execute
con.Open(); //open the connection to the database
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)//Check if the table has records
{
while (reader.Read()) //read all records with the given AccountNo
{
Transaction Transaction001 = new Transaction(reader.GetInt32(0), reader.GetDateTime(1), reader.GetString(2), reader.GetString(3), reader.GetDouble(4)); //New Transaction node
Transactions.AddFirst(Transaction001);// add the node to the Doubly Linked List (Transactions)
}
}
else
{
MessageBox.Show("No records found");
}
PrintNodes(Transactions);
reader.Close();
con.Close();
}
public void PrintNodes(LinkedList<Transaction> values)
{
if (values.Count != 0)
{
txtOutput.Text += "Here are your transaction details:";
**foreach (Transaction t in values)**
{
txtOutput.Text += "\r\n" + t;
}
txtOutput.Text += "\r\n";
}
else
{
txtOutput.Text += "The Doubly Linked List is empty!";
}
}
答案 0 :(得分:2)
将类型的实例(string
除外)转换为字符串时,例如:
txtOutput.Text += "\r\n" + t;
CLR(.NET运行时)将在传递的对象上调用方法ToString()
。这是一种方法,所有类型派生自System.Object
(.NET中很少有类型,不是从Object
派生的)继承。
但是默认实现只返回类型的名称。
您需要覆盖类型中的Object.ToString()
。并返回一个更有意义的字符串。
例如
public class Transaction {
//...
public override string ToString() {
// Guess field names from constructor:
// new Transaction(reader.GetInt32(0), reader.GetDateTime(1), reader.GetString(2), reader.GetString(3), reader.GetDouble(4))
return String.Format("#{0}: {1} {2} {3} {4} {5}", id, timestamp, string1, string2, number);
}
// ...
理想情况下,还应该存在溢出说话IFormatProvider
并将其传递给格式化函数(并且String.Format
将使用此类方法(如果可用))。更好地实施IFormattable
。
答案 1 :(得分:0)
覆盖Transaction类中的ToString方法。 默认情况下,它输出类型的名称。当您调用它时,这会隐式发生:
txtOutput.Text += "\r\n" + t;