-1

我正在关注这个 C# 教程http://csharp-station.com/Tutorial/CSharp/Lesson20,这是一个初学者问题。

下面我正在创建一个新的字典集合客户客户公共但不是静态类。简单的问题是我不能在我的方法中使用该customers.Add行。static void main我在这里想念什么?客户也必须是静态的吗?我应该在这里做什么才能创建客户对象。

Dictionary<int, Customer> customers = new Dictionary<int, Customer>();

Customer cust1 = new Customer(1, "Cust 1");
Customer cust2 = new Customer(2, "Cust 2");
Customer cust3 = new Customer(3, "Cust 3");

customers.Add(cust1.ID, cust1);
customers.Add(cust2.ID, cust2);
customers.Add(cust3.ID, cust3);

foreach (KeyValuePair<int, Customer> custKeyVal in customers)
{
    Console.WriteLine(
        "Customer ID: {0}, Name: {1}",
        custKeyVal.Key,
        custKeyVal.Value.Name);
}
4

1 回答 1

2

您的代码工作正常。我无法打开您发布的链接,但我猜您在此过程中误解了一些东西。

您不能从静态上下文访问类的非静态成员。让我解释...

class Foo
{
    int id;
    static void doStuff()
    {
        id++; // <-- Error!
    }
}

但这很好:

class Foo
{
    static void doStuff()
    {
        var fooBar = new Dictionary<Foo, Bar>(); // Create instance
        fooBar.Add(new Foo(), new Bar()); // No error :)
    }
}

就此而言,这也是(请注意,我指id的是 的成员foo):

class Foo
{
    int id;
    static void doStuff()
    {
        var foo = new Foo(); // Create instance
        foo.id++; // No error :)
    }
}

只要确保你的程序类看起来像这样......

public static class Program
{
    public static void Main()
    {
        Dictionary<int, Customer> customers = new Dictionary<int, Customer>();

        Customer cust1 = new Customer(1, "Cust 1");
        Customer cust2 = new Customer(2, "Cust 2");
        Customer cust3 = new Customer(3, "Cust 3");

        customers.Add(cust1.ID, cust1);
        customers.Add(cust2.ID, cust2);
        customers.Add(cust3.ID, cust3);

        foreach (KeyValuePair<int, Customer> custKeyVal in customers)
        {
            Console.WriteLine(
                "Customer ID: {0}, Name: {1}",
                custKeyVal.Key,
                custKeyVal.Value.Name);
        }
    }
}
于 2013-03-19T20:03:06.407 回答