You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决C# EpiServer Helper中并非所有代码路径都返回值报错

错误原因

  • 编译错误:你的GetSelections方法声明返回IEnumerable<ISelectItem>类型,目前仅在CoreStories不为空的if分支内有返回语句,当条件不满足时方法没有返回任何值,因此触发编译错误。
  • 空判断不完整:你当前只判断了最后一层CoreStories是否为空,但之前的InsightsConfiguration、CoreStoriesConfig两个属性也可能为null,依然会触发空引用异常。

修复后代码

using EPiServer;
using EPiServer.Shell.ObjectEditing;
using EPiServer.Web;
using System.Collections.Generic;
using System.Linq;

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);

            // 逐层空判断,任意一层为null则coreStories为null
            var coreStories = startPage.InsightsConfiguration?.CoreStoriesConfig?.CoreStories;
            if (coreStories == null || !coreStories.Any())
            {
                // 空场景返回空集合,满足所有代码路径都有返回值
                return Enumerable.Empty<ISelectItem>();
            }

            // 用LINQ简化转换逻辑,无需手动操作数组
            return coreStories.Select(story => new SelectItem() { Text = story, Value = story }).ToList();
        }
    }
}

改动说明

  • 用C#空条件运算符?.逐层访问属性,避免中间属性为null时触发空引用异常
  • 空配置场景返回Enumerable.Empty<ISelectItem>()空集合,解决编译错误,同时符合Episerver选择工厂的预期行为,后台编辑界面不会报错
  • 用LINQ简化集合转换逻辑,代码更简洁易维护

内容的提问来源于stack exchange,提问作者BrokenCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 15:48:00