gpt4 book ai didi

c# - .net 从抽象类创建对象实例

转载 作者:行者123 更新时间:2023-11-30 22:42:06 24 4
gpt4 key购买 nike

我有以下抽象类:

public abstract class TemplateBase
{
public abstract string TemplateName { get; }
public string RuntimeTypeName { get { return GetType().FullName; } }
public abstract List<AreaContainer> TemplateAreas { get; }
}

然后是这2个继承类:

public class SingleColumnTemplate : TemplateBase
{
public override string TemplateName { get { return "Single column"; } }

public AreaContainer CenterColumn { get; private set; }

public SingleColumnTemplate()
{
this.CenterColumn = new AreaContainer("Middle");
}

private List<AreaContainer> templateAreas;

public override List<AreaContainer> TemplateAreas
{
get
{
if (this.templateAreas == null)
{
this.templateAreas = new List<AreaContainer>() { this.CenterColumn };
}

return this.templateAreas;
}
}
}

public class TwoColumnTemplate : TemplateBase
{
public override string TemplateName { get { return "Two column"; } }
public AreaContainer LeftColumn { get; private set; }
public AreaContainer RightColumn { get; private set; }

public TwoColumnTemplate()
{
LeftColumn = new AreaContainer("Left");
RightColumn = new AreaContainer("Right");
}

private List<AreaContainer> templateAreas;

public override List<AreaContainer> TemplateAreas
{
get
{
if (this.templateAreas == null)
{
this.templateAreas = new List<AreaContainer>() { this.LeftColumn, this.RightColumn };
}
return this.templateAreas;
}
}
}

我也有这个类是我的编辑模型:

public class ContentPage
{
public virtual int ContentPageId { get; set; }

public virtual string Title { get; set; }

public TemplateBase Template { get; set; }
}

问题:

对于我的 ActionResults,我有以下内容:

[HttpGet]
public ActionResult Edit()
{
var row = new ContentPage();
var template = new TwoColumnTemplate();

// Areas
HtmlArea html_left = new HtmlArea();
html_left.HtmlContent = "left area html content";

HtmlArea html_right = new HtmlArea();
html_right.HtmlContent = "right area html content";

template.LeftColumn.Areas.Add(html_left);
template.RightColumn.Areas.Add(html_right);

row.Template = template;
return View(row);
}

[HttpPost]
[ValidateInput(false)]
public ActionResult Edit(ContentPage row)
{
// Here i could loop through List -TemplateAreas and save each template Area to Db. I guess that would work

return this.View(row);
}

问题:

对于 HttpGet- 我将如何从数据库加载行模板?因为它可能是 SingleColumnClass 或 TwoColumnClass。

我的 ViewModel 如何解决这个问题?

谢谢

最佳答案

您可以编写自己的模型绑定(bind)器,负责绑定(bind) TemplateBase。您仍然需要知道(在模型绑定(bind)器中)您将使用哪种类型的运行时,但您始终可以将其委托(delegate)给某种工厂或服务定位器。我做了一个快速的谷歌搜索,这是我发现的一篇博客文章,它为您提供了为类似场景制作模型 Binder 的一些信息:

http://weblogs.asp.net/bhaskarghosh/archive/2009/07/08/7143564.aspx

编辑:该博客省略了您如何向 MVC 告知您的模型绑定(bind)器。当应用程序启动时,您可以将模型绑定(bind)器添加到 System.Web.Mvc.ModelBinders.Binders

HTH

关于c# - .net 从抽象类创建对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4592925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com