在static void main中使用非静态自定义类

时间:2013-03-19 19:59:35

标签: c#

我正在关注这个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);
}

1 个答案:

答案 0 :(得分: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);
        }
    }
}