【问题标题】:MVC Model Class CastingMVC 模型类铸造
【发布时间】:2014-12-26 16:50:39
【问题描述】:

我有一个 asp.net mvc 应用程序。我有两个这样的模型类:

public class BaseViewModel
{
    ...
}

public class DerivedViewModel : BaseViewModel
{
    ...
}

我有一个视图,我想在这两个模型中都使用这个视图。

@model BaseViewModel
...

内部视图,我可以这样使用:

@if (Model.GetType() == DerivedViewModel)){
@* Properties of Derived class *@
}

我在这个视图中使用这样的表单:

@using (Html.BeginForm("Home", "Application", FormMethod.Post)) {
...
}

但是当我将表单发布到控制器方法时,我无法将基类转换为派生类。如何在控制器方法中分离派生类和基类?怎样才能正确发帖?

【问题讨论】:

标签: asp.net-mvc inheritance view model


【解决方案1】:

想象一下:

class Point
{
    int x { get; set; }
    int y { get; set; }
}
class Pixel : Point
{
    string RGB { get; set; }
}

Pixel 类继承自 Point,因此 Pixel 对象将具有 Point 特征,但反之则不然。看看:

var point = new Point { x = 1; y = 10; } // point object do not have RGB property;
var pixel = new Pixel { x = 1; y = 10; RGB = "#FFF" } // no comments needed :)

现在,有了这些对象,您就可以进行投射了。但是根据每种方式,您将进行向下转换或向上转换。

var pointOfPixel = (Point)pixel; // upcasting, but will "loose" the RGB property
var pixelFromPoint = (Pixel)point; // downcasting, a RGB property will be available with no value

如需更深入的信息,请阅读 Phil Curnow 的这篇文章: Polymorphism, Up-casting and Down-casting

【讨论】:

    猜你喜欢
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 1970-01-01
    相关资源
    最近更新 更多