C# 将对象添加到列表时出现空引用异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17096803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:34:57  来源:igfitidea点击:

Null Reference Exception When adding object to list

c#c#-4.0

提问by zerodoc

I keep getting an NullReferenceException when I try to add an object to a list inside an object, even when all properties of the object contains data. Classes--

当我尝试将一个对象添加到一个对象内的列表时,我不断收到 NullReferenceException,即使该对象的所有属性都包含数据。班级——

public class OrderInfo
    {
        public virtual string OrderNum { get; set; }
        public virtual string TrackingNum { get; set; }
        public virtual DateTime Shipdate { get; set; }
        public virtual string Cost { get; set; }
        public virtual string ShipMethod { get; set; }
        public virtual string ShipService { get; set; }
        public virtual string Country { get; set; }
        public virtual decimal Weight { get; set; }
        public virtual List<OrderItemInfo> OrderiTems { get; set; }

        public void AddShipmentItem(OrderItemInfo oi)
        {
            this.OrderiTems.Add(oi); // NULL Reference HERE
        }

    }

    public class OrderItemInfo
    {
        public virtual string OrderItemCode { get; set; }
        public virtual decimal? Quantity { get; set; }
        public virtual decimal? Cost { get; set; }
        public virtual decimal? Weight { get; set; }
        public virtual string Store { get; set; }
    }

Then I have code that catches if any nullable data is there.

然后我有代码来捕捉是否有任何可为空的数据。

private static OrderInfo GetOrderInfo(DataRow dr)
    {
        SqlConnection ShipworksConnectionString = 
        SqlCommand ShipworksCmd = new SqlCommand("SELECT OrderItem.Code,  

        InternationalShipmentCostAnalysisApp.OrderInfo ip = new      InternationalShipmentCostAnalysisApp.OrderInfo
            {
                OrderNum = (dr[0] is DBNull) ? String.Empty : dr[0].ToString(),
                TrackingNum = (dr[1] is DBNull) ? String.Empty : dr[1].ToString(),
                Shipdate = (dr[2] is DBNull) ? DateTime.MinValue :  Convert.ToDateTime(dr[2]),
                Cost = (dr[3] is DBNull) ? String.Empty : dr[3].ToString(),
                ShipMethod = (dr[4] is DBNull) ? String.Empty : dr[4].ToString(),
                ShipService = (dr[5] is DBNull) ? String.Empty : dr[5].ToString(),
                Country = (dr[6] is DBNull) ? String.Empty : dr[6].ToString(),
                Weight = (dr[7] is DBNull) ? 0 : Convert.ToDecimal(dr[7])

            };

        ShipworksConnectionString.Open();

        SqlDataReader rdr = ShipworksCmd.ExecuteReader();
        DataTable dt = new DataTable();

        dt.Load(rdr);
        rdr.Close();
        ShipworksConnectionString.Close();

        foreach (DataRow item in dt.Rows)
        {
            if (item != null)
            {
                InternationalShipmentCostAnalysisApp.OrderItemInfo i = new InternationalShipmentCostAnalysisApp.OrderItemInfo
                {
                    OrderItemCode = (item[0] is DBNull) ? String.Empty : item[0].ToString(),
                    Quantity = (item[1] is DBNull) ? 0 : Convert.ToDecimal(item[1]),
                    Cost = (item[2] is DBNull) ? 0 : Convert.ToDecimal(item[2]),
                    Weight = (item[3] is DBNull) ? 0 : Convert.ToDecimal(item[3]),
                    Store = (item[4] is DBNull) ? String.Empty : item[4].ToString()

                };

                ip.AddShipmentItem(i);
            }

        }


        return ip;
    }

采纳答案by Haney

It seems you never SET your property... You have it defined as a List<OrderItemInfo>typebut you never initialize it to an instanceof that type. Try initializing it in a constructor:

似乎您从未设置过您的属性...您已将其定义为一种List<OrderItemInfo>类型,但从未将其初始化为该类型的实例。尝试在构造函数中初始化它:

public class OrderInfo
{
    public OrderInfo
    {
        OrderiTems = new List<OrderItemInfo>();
    }
}

回答by Fabian Bigler

Is DbNull is not the same as Is NULL!

Is DbNull 与 Is NULL 不同!

You need to check for 'IS NULL', instead. That is why you are getting Null Reference Exceptions.

相反,您需要检查“IS NULL”。这就是您收到空引用异常的原因。

EDIT:as ebyrob got it right, the following line throws the exception:

编辑:由于 ebyrob 做对了,以下行引发异常:

this.OrderiTems.Add(oi); // NULL Reference HERE

回答by Fabian Bigler

OrderiTemsis null.

OrderiTemsnull

public virtual List<OrderItemInfo> OrderiTems { get; set; }

Try implementing set/get or storing an empty list into OrderiTemsin the constructor.

尝试OrderiTems在构造函数中实现 set/get 或存储一个空列表。

回答by dna

You need to instanciate the list before starting using it. A good place to do that is in the class constructor. Assuming you use the default constructor :

在开始使用它之前,您需要实例化该列表。这样做的一个好地方是在类构造函数中。假设您使用默认构造函数:

public OrderInfo()
{
    this.OrderiTems = new List<OrderItemInfo>();
}