Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

c# - 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 "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?

question from:https://stackoverflow.com/questions/65928628/i-have-a-problem-making-a-variables-that-can-be-used-in-other-methods-and-addi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...