【问题标题】:Object reference not set to an instance of an object...Error?对象引用未设置为对象的实例...错误?
【发布时间】:2012-08-31 18:08:13
【问题描述】:

好的,我对 C# 完全陌生,正在尝试调试错误。基本上我正在尝试为 SharePoint 列表创建一个 EventReceiver...这是在调试时给我对象引用错误的代码:

   public override void ItemAdding(SPItemEventProperties properties)
   {
       base.ItemAdding(properties);

       SPListItem item = properties.ListItem;

       if (item["Name"] == null)
           return; //or better yet, log 

       string oldFileName = item["Name"].ToString();

我正在做的是进入调试模式,并选择将文件添加到 SharePoint 库(这是在 ItemAdding 事件中),现在在我选择要上传的文件后显示此错误,知道为什么吗?

感谢您的帮助!

【问题讨论】:

  • 你应该用sharepoint标记这个问题
  • 你确定properties.ListItem 不为空吗?

标签: c# sharepoint event-handling sharepoint-list event-receiver


【解决方案1】:

这不是“对象引用错误”,而是NullReferenceException 是由于您尝试访问item 的索引运算符null 而引起的。

您可以通过在if 语句的行中设置断点并将鼠标悬停在不同的变量上来发现这一点。

要解决此问题,请确保 properties.ListItem 包含非空值或在 if: 中插入另一个检查:

if (item == null || item["Name"] == null)

【讨论】:

  • 谢谢!这似乎可行,我尝试使用断点,但是,一旦我进入调试模式,我的断点就会变成黄色并悬停在它上面我收到消息“断点不会被命中。没有为此文档加载任何符号”知道为什么这是?
  • @TudorHofnar 尝试让它继续运行,最终将加载符号并命中断点。
  • relevant SO question 提供了一些可能的解决方案。
  • @StanR。我让它运行了大约 10 分钟,断点仍然没有加载(当我回复电子邮件时哈哈)
  • @codesparkle 我阅读了该线程并尝试了一些选项,但没有任何效果。右键单击解决方案 --> 属性 查看 Common Properties --> Startup Project 选择多个启动项目,在需要调试的项目上选择 Start action。特别是我无法执行该解决方案,因为我找不到 Common Properties,我在 Even Receiver 项目中执行所有这些操作。知道如何尝试吗?
【解决方案2】:

您可能收到了错误,因为SPListItem item 为空。您不能访问空变量。您可以尝试将代码更新为:

       SPListItem item = properties.ListItem;

       if (item == null || item["Name"] == null) 
           return; //or better yet, log

【讨论】:

    【解决方案3】:
    SPListItem item = properties.ListItem;
    System.Debug.Assert(item != null, "item is null.");
    
    
    if (item["Name"] == null) --DEBUGGER STOPS HERE
        return; //or better yet, log 
    

    似乎item 或更具体的properties.ListItem 为空! 因为item 只是一个参考。

    【讨论】:

    • properties.ListItemitem 都是引用。
    猜你喜欢
    • 2011-07-09
    • 2011-11-21
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2012-09-19
    相关资源
    最近更新 更多