如何在 C# Helper for EpiServer 中绕过"Not all code paths return a value"



我有一个helper类,在我们向实例添加一个额外的站点之前,它在EpiServer中工作得很好。现在我们已经添加了一个额外的站点,helper抛出一个空引用,因为新的Startpage没有任何InsightsConfiguration.CoreStoriesConfig.CoreStories

我正试图重写下面的代码来解释这个空引用:

using EPiServer;
using EPiServer.Shell.ObjectEditing;
using EPiServer.Web;
using System.Collections.Generic;
namespace Digital.Site.Helpers.Selections
{
public class DataLayerCoreStorySelectionFactory : ISelectionFactory
{
public IEnumerable<ISelectItem> GetSelections(ExtendedMetadata metadata)
{
var loader = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentLoader>();
var startPage = loader.Get<Models.Pages.StartPage>(SiteDefinition.Current.StartPage);
var coreStories = startPage.InsightsConfiguration.CoreStoriesConfig.CoreStories;
ISelectItem[] selectItems = new ISelectItem[coreStories.Count];
int i = 0;
foreach (var story in coreStories) {
selectItems[i++] = new SelectItem() { Text = story, Value = story};
}
return selectItems;
}
}
}

我已经试过了:

using EPiServer;
using EPiServer.Shell.ObjectEditing;
using EPiServer.Web;
using System;
using System.Collections.Generic;
namespace Digital.Site.Helpers.Selections
{
public class DataLayerCoreStorySelectionFactory : ISelectionFactory
{
public IEnumerable<ISelectItem> GetSelections(ExtendedMetadata metadata)
{
var loader = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentLoader>();
var startPage = loader.Get<Models.Pages.StartPage>(SiteDefinition.Current.StartPage);
if (startPage.InsightsConfiguration.CoreStoriesConfig.CoreStories != null)
{
var coreStories = startPage.InsightsConfiguration.CoreStoriesConfig.CoreStories;
ISelectItem[] selectItems = new ISelectItem[coreStories.Count];
int i = 0;
foreach (var story in coreStories)
{
selectItems[i++] = new SelectItem() { Text = story, Value = story };
}
return selectItems;
}

}
}
}

但是这会抛出以下错误,我不确定如何解决:

' DataLayerCoreStorySelectionFactory.GetSelections (ExtendedMetadata):并非所有代码路径都返回值

public IEnumerable<ISelectItem> GetSelections(ExtendedMetadata metadata)
{
var loader = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentLoader>();
var startPage = loader.Get<Models.Pages.StartPage>(SiteDefinition.Current.StartPage);
if (startPage.InsightsConfiguration.CoreStoriesConfig.CoreStories != null)
{
var coreStories = startPage.InsightsConfiguration.CoreStoriesConfig.CoreStories;
ISelectItem[] selectItems = new ISelectItem[coreStories.Count];
int i = 0;
foreach (var story in coreStories)
{
selectItems[i++] = new SelectItem() { Text = story, Value = story };
}
return selectItems; // first code path
}
// return null; // second path
throw new CustomException("CoreStories is null"); // if you expect it in the if
}

这个错误基本上是说你的代码有多个路径。在你的例子中,你用if分岔路径。想象一下当条件为false时会发生什么,在这种情况下应该返回什么?然后说"这不会发生"是不正确的,因为在这种情况下你不需要if。

每个if都有一个可以写的显式else,或者隐式的&;else&;当条件解算为false

时发生。

相关内容

  • 没有找到相关文章

最新更新