Are there “Records” in C#?

2019-06-25 00:46发布

问题:

I'm looking to store some customer data in memory, and I figure the best way to do that would be to use an array of records. I'm not sure if that's what its called in C#, but basically I would be able to call Customer(i).Name and have the customers name returned as a string. In turing, its done like this:

type customers :
    record
        ID : string
        Name, Address, Phone, Cell, Email : string
        //Etc...
    end record

I've searched, but I can't seem to find an equivalent for C#. Could someone point me in the right direction?

Thanks! :)

回答1:

Okay, well that would be defined in a class in C#, so it might look like this:

public class Customer
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string Cell { get; set; }
    public string Email { get; set; }
}

Then you could have a List<T> of those:

var customers = new List<Customer>();

customers.Add(new Customer
{
    ID = "Some value",
    Name = "Some value",
    ...
});

and then you could access those by index if you wanted:

var name = customers[i].Name;

UPDATE: as stated by psibernetic, the Record class in F# provides field level equality out of the gate rather than referential equality. This is a very important distinction. To get that same equality operation in C# you'd need to make this class a struct and then produce the operators necessary for equality; a great example is found as an answer on this question What needs to be overridden in a struct to ensure equality operates properly?.



回答2:

A class or a struct would work here.

    class Customer
    {
        string Name
        {
            get;
            set;
        }
        string Email
        {
            get;
            set;
        }
    }

    Customer[] customers = new Customer[50];
    //after initializing the array elements, you could do
    //assuming a for loop with i as index
    Customer currentCustomer = customers[i];
    currentCustomer.Name = "This";


回答3:

It appears that the "type" you are looking for is actually a Class.

class Customer {
  string id, name, phone, cell, email;
}

List<Customer> customerList = new List<Customer>();

Check this link for more detail on classes... you may want to do a bit of research, reading and learning :-)

http://msdn.microsoft.com/en-us/library/vstudio/x9afc042.aspx



回答4:

Assuming you have a class which models your customers, you can simply use a List of customers.

var c = new List<Customers>()

string name = c[i].Name