0

我有以下激活码:

    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        // Create a new list and populate it.
        using (SPWeb web = properties.Feature.Parent as SPWeb)
        {
            web.Lists.Add("Projects", "Projects That are currently being worked on.", SPListTemplateType.GenericList);
            web.Update();

            // Add the new list and the new content.
            SPList projectList = web.Lists["Projects"];
            projectList.Fields.Add("Name", SPFieldType.Text, false);
            projectList.Fields.Add("Description", SPFieldType.Text, false);
            projectList.Update();

            //Create the view? - Possibly remove me.
            System.Collections.Specialized.StringCollection stringCollection = 
                new System.Collections.Specialized.StringCollection();
            stringCollection.Add("Name");
            stringCollection.Add("Description");

            //Add the list.
            projectList.Views.Add("Project Summary", stringCollection, @"", 100, 
                true, true, Microsoft.SharePoint.SPViewCollection.SPViewType.Html, false);
            projectList.Update();
        }
    }

应该通过并添加一个名为 project 的新列表及其相关视图。如何在运行应用程序时得到:

“激活功能”:对象引用未设置为对象的实例

我的问题是:

  • 为什么会这样?激活发生在站点级别。我是“开发”网站的管理员
  • 我是否应该每次都检查以确保此列表不存在?(每次,指的是我每次点击部署)
4

1 回答 1

1

I'm going to assume that you have a Site scoped feature and that your NullReferenceException is being caused by you attempting to cast properties.Feature.Parent as SPWeb.

If my assumption about your feature being Site scoped is correct you can't get access to an SPWeb the way you are trying. Try this instead:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPSite siteCollection = properties.Feature.Parent as SPSite;
    if (siteCollection != null) 
    {
        SPWeb web = siteCollection.RootWeb;
        // Rest of your code here.
    }
}
于 2013-06-04T15:18:19.420 回答