C#对象引用未设置为对象的实例.在列表中实例化类? [英] C# Object reference not set to an instance of an object. Instantiating Class within a List?

查看:522
本文介绍了C#对象引用未设置为对象的实例.在列表中实例化类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class OrderItem
{
    public string ProductName { get; private set; }
    public decimal LatestPrice { get; private set; }
    public int Quantity { get; private set; }
    public decimal TotalOrder { get {return LatestPrice * Quantity;}}

    public OrderItem(string name, decimal price, int quantity)
    {

    }

    public OrderItem(string name, decimal price) : this(name, price, 1)
    {

    }
}

以上是该课程,只是出于某些背景.

Above is the class, just for some background.

public void AddProduct(string name, decimal price, int quantity)
{
    lstOrderitem.Add(new OrderItem(name, price, quantity));           
}

在AddProduct方法内的代码上,我得到标题中指出的错误.

On the code inside the AddProduct method is where I am getting the error stated in the title.

我只是想实例化该类并将其添加到要显示在表单程序列表框中的集合中.

I'm just trying to instantiate the class and add it to a collection to be displayed in a listbox on my form program.

将在按钮单击事件中调用"AddProduct"

The "AddProduct" will be called on a button click event

Error = NullReferenceException-对象引用未设置为对象的实例.

Error = NullReferenceException - Object reference not set to an instance of an object.

我想知道是否有人知道为什么会发生这种情况,因为我认为自从创建类的一个NEW实例并将其添加到列表中以来,它也将要引用一些东西.谢谢大家知道问题出在哪里.

I was wondering if anybody knew why this was happening since I thought that since I am making a NEW instance of the class while adding it to the list that it would have something to reference too. Thank you if anybody knows what the problem is.

编辑

    public List<OrderItem> lstOrderitem{ get; private set; }
    public int NumberOfProducts { get; private set; }
    public decimal BasketTotal { get; private set; }

    public ShoppingBasket()
    {
        //List<OrderItem> lstOrderitem = new List<OrderItem>();
    }

    public void AddProduct(string name, decimal price, int quantity)
    {
        lstOrderitem.Add(new OrderItem(name, price, quantity));


    }

推荐答案

您应在构造函数中初始化lstOrderitem属性,如下所示:

You should initialize lstOrderitem property in the constructor, like this:

编辑

public MyClass() {
    lstOrderitem = new List<OrderItem>();
}

P.S. Microsoft建议您以大写字母开头的属性名称,以避免与成员变量混淆,成员变量应以小写字母开头.

P.S. Microsoft suggests starting the names of your properties in capital letters, to avoid confusion with member variables, which should be named starting with a lowercase letter.

这篇关于C#对象引用未设置为对象的实例.在列表中实例化类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆