【发布时间】:2019-05-28 16:29:19
【问题描述】:
在此处和 PluralSight 上的以下教程对 c# 非常陌生。
我有以下文件(我认为是类?)
程序.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Customers
{
class Program
{
static void Main(string[] args)
{
CustomerList customers = new CustomerList();
customers.AddCustomer("Apple");
customers.AddCustomer("Microsoft");
}
}
}
还有 CustomerList.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Customers
{
public class CustomerList
{
public CustomerList()
{
customers = new List<string>();
}
public void AddCustomer(string customer)
{
customers.Add(customer);
}
private List<String> customers;
}
}
我遇到的问题是我只想列出列表中的项目,这样做让我很难过。我确实尝试使用如下的 foreach 语句。
foreach (string customer in customers)
{
Console.WriteLine(customer);
}
来自 Program.cs 但我无法按照它的说明这样做
“foreach 语句无法对'CustomerList' 类型的变量进行操作,因为'CustomerList' 不包含'GetEnumerator' 的公共实例定义”
但是,如果我将所有代码保存在 Program.cs 中并使用以下代码,我就可以写出列表中的每个项目。
private List<string> customers;
static void Main(string[] args)
{
customers = new List<String>();
AddCustomers(customers);
foreach(string customer in customers) {
Console.WriteLine(customer);
}
}
private void AddCustomers(List<string> customers)
{
customers.Add("Apple");
customers.Add("Microsoft");
}
就像我说的,很新,所以请放轻松。
【问题讨论】:
-
首先,您为什么还要开设
CustomerList课程?只需改用List<string>。 -
问题是什么?
-
您的 CustomerList 类中的“客户”列表无法从该类外部访问。