开发者

How to cast a ViewModel to another ViewModel?

I have two ViewModels which are similar, and i need to cast one to another.

This is the first one:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestInheritance.Models
{
    public class ShowMatrixQuestionViewModel : ShowQuestionViewModel
    {
        public Dictionary<MatrixRows, List<MatrixColumns>> columnrow;
        public List<MatrixColumns> columns;
        public List<MatrixRows> rows;

        public ShowMatrixQuestionViewModel()
        {
            columns = new List<MatrixColumns>();
            rows = new List<MatrixRows>();
            columnrow = new Diction开发者_运维知识库ary<MatrixRows, List<MatrixColumns>>();
        }
    }

    public class MatrixColumns
    {
        public int Column_ID { get; set; }
        public int Column_Number { get; set; }
        public String Column_Description { get; set; }
        public Boolean IsAnswer { get; set; }
        public int Procent { get; set; }
    }

    public class MatrixRows
    {
        public bool Delete { get; set; }
        public int Row_Id { get; set; }
        public String Row_Number { get; set; }
        public String Row_Description { get; set; }
    }

}

The second looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestInheritance.Models.ViewModels.New
{
    public class ShowMatrixProcentViewModel : ShowMatrixQuestionViewModel
    {
        // Dette er for at vi kan bruge DisplayTemplates
        public ShowMatrixProcentViewModel()
            : base()
        {
        }
    }
}

When i try to cast a ShowMatrixQuestionViewModel to a ShowMatrixProcentViewModel i get a InvalidCastException:

MatrixColumns mc = new MatrixColumns()
            {
                Column_Description = "Hej",
                Column_ID = 1,
                Column_Number = 1,
                IsAnswer = false
            };

            MatrixColumns mc2 = new MatrixColumns()
            {
                Column_Description = "Med",
                Column_ID = 1,
                Column_Number = 1,
                IsAnswer = false
            };

            MatrixRows mr = new MatrixRows()
            {
                Row_Description = "2005",
                Row_Id = 1,
                Row_Number = "1"
            };

            MatrixRows mr2 = new MatrixRows()
            {
                Row_Description = "2008",
                Row_Id = 1,
                Row_Number = "2"
            };

            List<MatrixColumns> matrixcolumns = new List<MatrixColumns>();
            matrixcolumns.Add(mc);
            matrixcolumns.Add(mc2);
            List<MatrixRows> matrixrows = new List<MatrixRows>();
            matrixrows.Add(mr);
            matrixrows.Add(mr2);

            ShowMatrixQuestionViewModel avm = new ShowMatrixQuestionViewModel()
            {
                IsAnswered = true,
                Question_ID = 1,
                Question_Number = "1",
                Question_Type = "hej",
                Question_Wording = "spørgsmål1",
                Visible = true,
                columns = matrixcolumns,
                rows = matrixrows
            };

            ShowMatrixProcentViewModel sm = (ShowMatrixProcentViewModel)avm;

return View(avm);

The exception says:

System.InvalidCastException: Unable to cast object of type 'TestInheritance.Models.ShowMatrixQuestionViewModel' to type 'TestInheritance.Models.ViewModels.New.ShowMatrixProcentViewModel'.

Do i need to initialize some stuff in the ShowMatrixProcentViewModel before i can cast??

Thanks in advance


Since ShowMatrixProcentViewModel inherit from ShowMatrixQuestionViewModel you can't just cast from ShowMatrixQuestionViewModel to ShowMatrixProcentViewModel. That's basic OO. You can only cast in the sub-class > super-class direction. The reason is that ShowMatrixQuestionViewModel doesn't contain everything that ShowMatrixProcentViewModel does.

You could use something like AutoMapper but your should probably look at your design/architecture instead since something like this is signs of bad structure.


You cannot cast between two unrelated types, even if they're similar.

You can only cast an object to a type that it actually is. (Or using a custom explicit cast).

Instead, you can use a library like AutoMapper to create one from the other.


You can cast ShowMatrixProcentViewModel in ShowMatrixQuestionViewModel but not viceversa:

ShowMatrixProcentViewModel p = new ShowMatrixProcentViewModel();

ShowMatrixQuestionViewModel q = p; //downcast: not need cast operator

ShowMatrixQuestionViewModel p1 = new ShowMatrixProcentViewModel();

ShowMatrixProcentViewModel p2 = (ShowMatrixProcentViewModel)p1; //upcast: need cast operator

ShowMatrixQuestionViewModel q1 = new ShowMatrixQuestionViewModel();

ShowMatrixProcentViewModel p3 = (ShowMatrixProcentViewModel)q1; //throws an exception


Additionally, to the coments made by others, if you want to build one view model out of another one, then I'd use constructor dependency injection:

OrderViewModel orderViewModel = new OrderViewModel(CustomerViewModel customerViewModel);

This is not great, but I guess that's what you are asking for.

Also it's a bad idea to inherit from a concrete class - it'll be time-consuming/difficult to make changes in future.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜