简体   繁体   中英

Question on C# Generic Collection

In the following code, the Type of our Dictionary is <int, Customer> , but how do I know what's the type of Customer? It seems like Customer is a string here since we're Customer cust1 = new Customer(1, "Cust 1"); .... im confused...

 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);
}

A Customer object is type Customer even though it consists of an int and a string . When you are calling Customer cust1 = new Customer(1, "Cust 1"); that is really saying "make me an object of type Customer which consists of the integer 1 and string Cust 1"

The type of Customer is Customer . A class is a user-defined type that can store other types in named fields (the other such kind of type is a struct ).

The place where a string is passed is called a constructor - a special method that sets up a new object. Here it accepts a string and stores it as the customer's name.

Your representation of Customer in the example is just an ID and a name.

You could represent it with many things, being an ID and name your chosen one for this case.

The cited sample is just a call to the constructor, where you inform the ID and the name of that specific customer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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