0

重写问题。

基本上我有这两个类:

class Show {
 public List<Episode> Episodes{ get; set; }
}

class Episode {
 public Show Show{ get; set; }
}

当我向节目添加剧集时,我必须创建一个新的剧集对象。但是,当我这样做时,我还必须填写节目,这变成了一个循环问题。我怎样才能将一集添加到一个节目中,该剧集还包含对其所属节目的引用,而不会以一个永恒的循环结束?

我想我遗漏了一些重要信息:

我有一个为我创建视图模型的工厂。CreateShowViewModel当我想要一个节目列表时,请在列表中的每个节目上调用该方法。该方法如下:

    public ShowViewModel CreateShowViewModel(Show show) {
        return new ShowViewModel {
            ShowID = show.ShowID,
            Title = show.Title,
            Episodes = CreateEpisodeViewModels(show.Episodes)
        };
    }

当它必须实例化剧集时,它会调用一个方法,该方法对每个剧集执行以下功能:

    public EpisodeViewModel CreateEpisodeViewModel(Episode episode) {
        return new EpisodeViewModel {
            ShowID = episode.ShowID,
            EpisodeID = episode.EpisodeID,
            Title = episode.Title,
            Show = CreateShowViewModel(episode.Show)
        };
    }

这将再次创建节目,等等。这构成循环引用,不是吗?

4

1 回答 1

2

我可以看到这个问题的两个明显的解决方案。第一个是简单地传递一个可选的 ViewModel,所以你在方法调用中打破了循环。像这样的东西:

    public ShowViewModel CreateShowViewModel(Show show, List<EpisodeViewModel> episodes = null /* guessing type */) {
        var viewModel = new ShowViewModel {
            ShowID = show.ShowID,
            Title = show.Title
        };
        viewModel.Episodes = episodes ?? CreateEpisodeViewModels(show.Episodes, viewModel);
        return viewModel;
    }

    public EpisodeViewModel CreateEpisodeViewModel(Episode episode, ShowViewModel show = null) {
        var viewModel = new EpisodeViewModel {
            ShowID = episode.ShowID,
            EpisodeID = episode.EpisodeID,
            Title = episode.Title
        };
        viewModel.Show = show ?? CreateShowViewModel(episode.Show, viewModel); // this might cause a problem due to the fact that you only have 1 episode, and not all of them.
        return viewModel;
    }

另一种方法是从Show->ShowViewModelEpisode->添加一些兑现EpisodeViewModel。我建议ConditionalWeakTable为此使用 a 。

类似这样的东西:

static ConditionalWeakTable<Show, ShowViewModel> _shows = new ConditionalWeakTable<Show, ShowViewModel>();
static ShowViewModel GetForShow(Show show)
{
     return _shows.GetValue(show, s => CreateShowViewModel(s));
} // do the same for episode.
于 2013-06-08T23:45:22.307 回答