You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# OOP中创建可存储派生类对象的动态客户列表及静态成员报错咨询

解决你的C#客户列表代码问题

别担心,这个问题其实是C#新手非常容易碰到的静态成员 vs 实例成员的问题,和你怀疑的“派生类对象添加到基类列表”完全没关系——那个部分的写法是完全正确的!

错误根源:静态方法访问非静态字段

你看到的An object reference is required for the nonstatic field, method, or property 'member'错误,核心原因是:

  • customers是Program类的实例字段(没有加static修饰符),它属于Program类的具体对象;
  • 而GetCustomerInfo是静态方法,静态方法属于类本身,不属于任何具体对象,所以在静态方法里没办法直接访问实例字段。

两种可行的修复方案

方案1:把customers改成静态字段

直接给customers加上static修饰符,让它属于Program类本身,这样静态方法就能直接访问了:

class Program {
    static List<Customer> customers = new List<Customer>(); // 添加static修饰符
    // ... 其他代码不变
}

方案2:把GetCustomerInfo改成非静态方法

如果不想把列表设为静态,可以把GetCustomerInfo改成实例方法,然后在Main里创建Program的对象来调用它:

class Program {
    List<Customer> customers = new List<Customer>();
    static void Main(string[] args) {
        Program app = new Program(); // 创建类的实例
        app.GetCustomerInfo(); // 通过实例调用非静态方法
    }
    void GetCustomerInfo() { // 移除static修饰符
        // ... 方法内部代码不变
    }
}

代码里的其他小bug(顺便帮你修正)

除了核心错误,你的代码还有几个需要调整的小问题:

  1. 缺少产品2的输入提示:在输入prod2之前没有提示用户,应该加上:
    Console.Write("Quantity of product 2: ");
    bool success2 = false;
    while (!success2) {
        success2 = int.TryParse(Console.ReadLine(), out prod2);
    }
    
  2. 多余的添加客户代码:方法最后一行的customers.Add(new PickUpCustomer() { ... });是多余的,不管用户选自提还是配送,都会额外添加一个自提客户,直接删掉这行。
  3. 未给产品数量赋值:创建客户对象时,没有把输入的prod1和prod2赋值给Customer的对应属性,比如:
    customers.Add(new DeliveryCustomer() { 
        Name = name, 
        PhoneNumber = number, 
        Address = address,
        QuantityOfProductOne = prod1,
        QuantityOfProductTwo = prod2
    });
    

关于派生类添加到基类列表的疑问

你担心的这个点其实是完全正确的!在C#里,子类对象可以赋值给基类类型的变量、存入基类类型的集合,这就是多态的核心特性之一。以后你遍历customers列表时,可以通过is/as关键字判断客户类型,或者给Customer添加虚方法来实现不同客户的差异化逻辑,比如:

class Customer {
    // ... 现有代码
    public virtual string GetCustomerDetails() {
        return $"Name: {Name}, Phone: {PhoneNumber}, Products: {QuantityOfProductOne}x Prod1, {QuantityOfProductTwo}x Prod2";
    }
}

class DeliveryCustomer : Customer {
    // ... 现有代码
    public override string GetCustomerDetails() {
        return base.GetCustomerDetails() + $", Delivery Address: {Address}";
    }
}

修正后的完整代码

class Program {
    static List<Customer> customers = new List<Customer>();
    static void Main(string[] args) {
        GetCustomerInfo();
        // 测试输出,验证客户是否成功添加
        foreach(var customer in customers) {
            Console.WriteLine(customer.GetCustomerDetails());
        }
    }
    static void GetCustomerInfo() {
        int prod1, prod2;
        Console.WriteLine("Please enter the following info.");
        Console.WriteLine("Type '1' for delivery, '2' for pickup: ");
        string option = Console.ReadLine();
        Console.Write("Name: ");
        string name = Console.ReadLine();
        Console.Write("10 digit Phone Number: ");
        string number = Console.ReadLine();
        Console.Write("Quantity of product 1: ");
        bool success = false;
        while (!success) {
            success = int.TryParse(Console.ReadLine(), out prod1);
        }
        Console.Write("Quantity of product 2: "); // 添加产品2输入提示
        bool success2 = false;
        while (!success2) {
            success2 = int.TryParse(Console.ReadLine(), out prod2);
        }
        if(option == "1") {
            Console.WriteLine("Address: ");
            string address = Console.ReadLine();
            customers.Add(new DeliveryCustomer() { 
                Name = name, 
                PhoneNumber = number, 
                Address = address,
                QuantityOfProductOne = prod1,
                QuantityOfProductTwo = prod2
            });
        } else if (option == "2") {
            Console.WriteLine("Pick up time: ");
            string time = Console.ReadLine();
            customers.Add(new PickUpCustomer() { 
                Name = name, 
                PhoneNumber = number, 
                PickUpTime = time,
                QuantityOfProductOne = prod1,
                QuantityOfProductTwo = prod2
            });
        }
        // 移除多余的添加客户代码
    }
}
class Customer {
    static int productOnePrice = 5;
    static int productTwoPrice = 10;
    private string name;
    private string phoneNumber;
    private int quantityOfProductOne;
    private int quantityOfProductTwo;
    public Customer() {
        name = "";
        phoneNumber = "";
        quantityOfProductOne = 0;
        quantityOfProductTwo = 0;
    }
    public string Name { get => name; set => name = value; }
    public string PhoneNumber { get => phoneNumber; set {
            if(value.Length != 10) {
                Console.WriteLine("Invalid number. Must be 10 digits.");
            } else {
                phoneNumber = value;
            }
        } }
    public int QuantityOfProductOne { get => quantityOfProductOne; set => quantityOfProductOne = value; }
    public int QuantityOfProductTwo { get => quantityOfProductTwo; set => quantityOfProductTwo = value; }

    // 添加虚方法,方便后续扩展客户详情展示
    public virtual string GetCustomerDetails() {
        return $"Name: {Name}, Phone: {PhoneNumber}, Products: {QuantityOfProductOne}x Prod1, {QuantityOfProductTwo}x Prod2";
    }
}
class DeliveryCustomer : Customer {
    private string address;
    public string Address { get => address; set => address = value; }
    public DeliveryCustomer() {
        address = "";
    }

    public override string GetCustomerDetails() {
        return base.GetCustomerDetails() + $", Delivery Address: {Address}";
    }
}
class PickUpCustomer : Customer {
    private string pickUpTime;
    public string PickUpTime { get => pickUpTime; set => pickUpTime = value; }
    public PickUpCustomer() {
        pickUpTime = "";
    }

    public override string GetCustomerDetails() {
        return base.GetCustomerDetails() + $", Pickup Time: {PickUpTime}";
    }
}

内容的提问来源于stack exchange,提问作者Kyle Close

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 17:52:33