关于C#Generic Collection的问题

时间:2009-08-02 16:03:49

标签: c# generics

在下面的代码中,我们的词典类型是<int, Customer>,但我怎么知道客户的类型是什么?看来客户是一个字符串,因为我们是客户cust1 =新客户(1,“客户1”); ....我很困惑......

 public class Customer
    {
        public Customer(int id, string name)
        {
            ID = id;
            Name = name;
        }

    private int m_id;

    public int ID
    {
        get { return m_id; }
        set { m_id = value; }
    }

    private string m_name;

    public string Name
    {
        get { return m_name; }
        set { m_name = value; }
    }
}

 Dictionary<int, Customer> customers = new Dictionary<int, Customer>();

Customer cust1 = new Customer(1, "Cust 1");
Customer cust2 = new Customer(2, "Cust 2");
Customer cust3 = new Customer(3, "Cust 3");

customers.Add(cust1.ID, cust1);
customers.Add(cust2.ID, cust2);
customers.Add(cust3.ID, cust3);

foreach (KeyValuePair<int, Customer> custKeyVal in customers)
{
    Console.WriteLine(
        "Customer ID: {0}, Name: {1}",
        custKeyVal.Key,
        custKeyVal.Value.Name);
}

3 个答案:

答案 0 :(得分:8)

Customer对象的类型为Customer,即使它由intstring组成。当你调用Customer cust1 = new Customer(1, "Cust 1");时,真的说“让我成为Customer类型的对象,它包含整数1和字符串Cust 1”

答案 1 :(得分:6)

Customer的类型为Customerclass是用户定义的类型,可以在命名字段中存储其他类型(另一种类型是struct)。

传递字符串的位置称为构造函数 - 一种设置新对象的特殊方法。在这里它接受一个字符串并将其存储为客户的名字。

答案 2 :(得分:0)

示例中您对Customer的表示只是一个ID和一个名称。

你可以用很多东西来代表它,作为你所选择的ID和名称。

引用的示例只是对构造函数的调用,您可以在其中通知ID和特定客户的名称。

相关问题