繁体   English   中英

如何打印通用链表的内容?

[英]How to print the contents of a generic linked list?

我正在尝试打印名为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!";
    }
}

将类型的实例( 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

重写Transaction类中的ToString方法。 默认情况下,它输出类型的名称。 当你调用它时会隐式发生这种情况:

txtOutput.Text += "\r\n" + t;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM