简体   繁体   English

对象引用未设置为对象的实例[C#]

[英]Object reference not set to an instance of an object [C#]

I am getting the following error: 我收到以下错误:

Object reference not set to an instance of an object

I don't know what is the cause of this error and how to solve it, here is my code: 我不知道此错误的原因是什么以及如何解决,这是我的代码:

while(dr.Read())
    {
     string variant = dr.GetString(0);
     int size = dr.GetInt32(1);
     int quantity = dr.GetInt32(2);

     DataRow x = dt.Rows
                  .Cast<DataRow>()
                  .Where(r => r["variant_name"].Equals(variant) && r["size"].Equals(size))
                  .FirstOrDefault();
                  x["quantity"] = quantity;             

      }

I'm getting the error on this line -> x["quantity"] = quantity; 我在这条线上出现错误-> x["quantity"] = quantity; I'm wondering why it would give a null value because I checked in my database that it should return exactly one match. 我想知道为什么它会给出一个空值,因为我在数据库中检查它应该返回一个完全匹配的值。

如果找不到元素,并且您尝试访问此对象,则FirstOrDefault返回null。

On the last line x is null, fix with 在最后一行x为空,用

if(x != null)
   x["quantity"] = quantity;

This happens if your condition (.Where) doesn't yield a match. 如果您的条件(.Where)不匹配,则会发生这种情况。
At that point the FirstOrDefault return the Default part 此时, FirstOrDefault返回Default部分
and this is a null for a reference object as explained in MSDN 这是MSDN中解释的参考对象的null

The default value for reference and nullable types is null. 引用和可为null的类型的默认值为null。

while(dr.Read())
 {
  string variant = dr.GetString(0);
  int size = dr.GetInt32(1);
  int quantity = dr.GetInt32(2);

  DataRow x = dt.Rows
                .Cast<DataRow>()
                .Where(r => (r["variant_name"].ToString().Equals(variant) && Convert.ToInt32(r["size"]).Equals(size)))
                .FirstOrDefault();

   if (x != null)
   {
       x["quantity"] = quantity;  
   }       
 }

Thank you for your answer it helped me a lot. 谢谢您的回答,这对我很有帮助。 I just changed the line .Where a little bit and now it works for me. 我只是更改了线路.Where.Where有一点点,现在对我.Where Thank you again! 再次感谢你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM