开发者

viewModel as viewModelExtended, cast?

开发者 https://www.devze.com 2023-02-18 19:44 出处:网络
I have problems with how to do this. I have two classes; ProductViewModel and ProductExtendedViewModel.

I have problems with how to do this. I have two classes; ProductViewModel and ProductExtendedViewModel.

My scenario is basically that the ProductExtendedViewModel inherits the ProductViewModel and I want to cast ProductViewModel to ProductExtendedViewModel. How should I go about doing that?

This is what I have开发者_运维百科 tried so far without success:

viewModelExtended = (ViewModelExtended) viewModel;

I get the tip that when casting a number the value must be a number less then infinity

I'm not that great at inherits and casting so this is all kinda new to me so please understand the kinda newbee question.

thanks

EDIT

public class ProductViewModel
{
    public string Name { get; set; }
    public Product Product { get; set; }
}

public class ProductExtendedViewModel : ProductViewModel
{
    public string ExtendedName { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}


Sadly, in c# you can't cast from a Base Type to a Derived Type ("downcasting"), because you would be trying to generate information (i.e. what value should ExtendedName have?).

Your best bet would be to do this through composition - create a constructor on ProductExtendedViewModel that takes a ProductViewModel:

public class ProductExtendedViewModel : ProductViewModel
{
    public ProductExtendedViewModel()
    {
    }

    public ProductExtendedViewModel(ProductViewModel viewModel)
    {
        Name = viewModel.Name;
        Product = viewModel.Product;
    }

    public string ExtendedName { get; set; }
}

Which you could then call:

var productModel = new ProductViewModel {Name = product.Name, Product = product};

var derived = new ProductExtendedViewModel(productModel);

Note that you can still cast the Derived type back to it's base type, as this involves a loss of information:

var basetype = (ProductViewModel)derived;

I believe that the "Troubleshooting tip" of "When casting from a number [...]" is a red herring in this case, and is just a help around casting in general.


As Zhaph says you can't downcast in C#. An alternative to his solution would be to use AutoMapper to create the instance of the inheriting class. This would look like this:

var productExtendedViewModel = Mapper.Map<ProductViewModel, ProductExtendedViewModel>(productViewModel);

See the documentation for how you can configure the mapping, but the basic mapping would be created like this:

Mapper.CreateMap<ProductViewModel, ProductExtendedViewModel>();

AutoMapper is a good tool to handle all mappings between business objects and view models.

0

精彩评论

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