这是我第一次使用列表,但我似乎做得不太好。我有一个客户类,其中包含客户列表作为客户类中的属性(可以这样做吗?)
public class Customer
{
private List<Customer> customers = new List<Customer>();
public List<Customer> Customers
{
get { return customers; }
set { customers = value; }
}
在我的程序中,我像这样添加到这个客户列表中:
Customer C = new Customer();
Customer.InputCustomer(C);
C.Customers.Add(C);
现在我需要向列表中的客户展示。我已向 Customer 类添加了 AllCustomers 函数,如下所示:
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();
}
}
但我在 foreach 语句中收到此错误:
非静态字段、方法或属性“AddCustomerList.Customer.Customers.get”需要对象引用
就像我说的,这是我第一次使用List,也许我不明白,对吧?谁能帮帮我吗?
问题是您尝试访问非静态属性Customers
从一个内static http://msdn.microsoft.com/en-us/library/79b3xss3(VS.80).aspx method.
我怀疑你想要的是这样的:
public void AllCustomers()
{
// ...
(即去掉 static 修饰符)
或者你也可以两者都做customers
和Customers
成员也是静态的:
private static List<Customer> customers = new List<Customer>();
public static List<Customer> Customers
{
get { return customers; }
set { customers = value; }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)