An object reference is required for the non-static field, method, or property
This is the first time i am working with Lists and I don't seem to be getting it right. I have a Customer class with a list of customers as a property in the Customer class (can it be done like this?)
public class Customer
{
private List<Customer> customers = new List<Customer>();
public List<Customer> Customers
{
get { return customers; }
set { customers = value; }
}
In my program I add to this customer list like this:
Customer C = new Customer();
Customer.InputCustomer(C);
C.Customers.Add(C);
Now I need to show the customers in this list. I have added a AllCustomers function to the Customer Class like this:
public static void AllCustomers()
{
foreach (Customer customer in Customers) //Fail on "开发者_Go百科Customers"
{
Console.WriteLine("Customer ID: " + customer.ID);
Console.WriteLine("Customer Name: " + customer.FullName);
Console.WriteLine("Customer Address: " + customer.Address);
Console.WriteLine();
}
}
But I am getting this error in the foreach statement:
An object reference is required for the non-static field, method, or property 'AddCustomerList.Customer.Customers.get'
Like I said, this is the first time I am using List, maby i don't understand it right? Can anyone please help me?
The problem is that you attempting to access the non-static property Customers
from within a static method.
I suspect what you want is this:
public void AllCustomers()
{
// ...
(i.e. get rid of the static modifier)
Alternatively you can make both customers
and the Customers
members static too:
private static List<Customer> customers = new List<Customer>();
public static List<Customer> Customers
{
get { return customers; }
set { customers = value; }
}
It fails because AllCustomers()
is an static method. Remove the 'static' from it and it should compile and work as you expect.
As Gonzalo says, you need to remove static
from the AllCustomers
method.
Alternatively, you could pass in the list of customers to the AllCustomers method, which could continue to be static.
public static void AllCustomers(List<Customer> customers)
However, I'm curious as to why you have the Customers list inside the customers class - is this because your customers have their own customers?
精彩评论