c# - 以编程方式键入对象

标签 c# asp.net-mvc-4

以编程方式键入对象

C# mvc4 项目

我有两个相似的 ViewModel,其中包含十几个复杂的对象,我想从我的创建和编辑操作中调用一个通用方法来填充 ViewModel。

类似的东西

private void loadMdlDtl(CreateViewModel  cvM, EditViewModel evM)
{
  If (vM1 != null) { var vM = vM1}
  If (vM2 != null) { var vM = vM2}

  // about two dozen complex objects need to be populated
  vM.property1 = …;
  vM.property2 = …;
  …
}

这不起作用,因为 vM 不在范围内。

有没有什么方法可以以编程方式键入 vM 对象,这样我就不必创建两个 loadModel 方法或以其他方式重复大量代码?

解决方案:

创建接口(interface):

public interface IViewModels
{
    string property1 { get; set; }
    int property2 { get; set; }
    IEnumerable<ValidationResult> Validate(ValidationContext validationContext);
}

让 View 模型继承接口(interface):

public class CreateViewModel : IViewModels, IValidatableObject
{
  string property1 { get; set; }
  int property2 { get; set; }
  IEnumerable<ValidationResult> Validate(ValidationContext validationContext);
  {
    // implementation
  }
}

public class EditViewModel : IViewModels, IValidatableObject
{
  string property1 { get; set; }
  int property2 { get; set; }
  IEnumerable<ValidationResult> Validate(ValidationContext validationContext);
  {
    // implementation
  }
}

从传递 View 模型的 Actions 中调用方法:

public ActionResult Create()
{
  var vM = new CreateViewModel();
  ...
  loadMdlDtl(vM);
  ...
}

但现在接受接口(interface)而不是 View 模型进入方法:

private void loadMdlDtl(IViewModel vM)
{
  // implementation
}

最佳答案

由于您希望访问所有对象都相同的属性和/或方法,您可以定义一个具有此类属性和方法的接口(interface)。让每个对象实现该接口(interface)。

public interface IMyCommonStuff
{
    string property1 { get; set; }
    int property2 { get; set; }
    int SomeMethod();
}

更新

如果某些方法和/或属性具有相同的实现,则该实现可以在公共(public)基类型中完成。我建议在对对象执行操作时仍然使用接口(interface)定义。示例:

public class MyCommonImplementation : IMyCommonStuff
{
    public virtual int SomeMethod()
    {
        // Implementation goes here.
    }

    public string property1 { get; set; }

    public int property2 { get; set; }
}

public class MyConcreteSubclass : MyCommonImplementation, IMyCommonStuff
{
    // Add only the things that make this concrete subclass special.  Everything
    // else is inherited from the base class
}

关于c# - 以编程方式键入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20625119/

相关文章:

c# - 如何在 C# 中读取 Http 响应流两次?

javascript - MVC bundle 不工作

c# - .Net MVC4 重定向到操作未按预期工作

c# - ASP.NET MVC 4 代码优先,如何使用代码优先添加表

javascript - 如何使用 ASP.NET MVC 索引 View 分页中的页面大小下拉菜单?

c# - linq group by 投影到带有非参数构造函数的类

c# - WindowsIdentity 和经典 .Net 应用程序池

c# - 测试请求的 URL 是否在路由表中

C# MVC 调试哪个 Controller 返回 View

c# - 获取通过 Ajax 传递的 Controller 中的 Json.Stringify 值