我对如何执行此操作有疑问。我有两个类(class); ProductViewModel 和 ProductExtendedViewModel。
我的场景基本上是 ProductExtendedViewModel 继承了 ProductViewModel,我想将 ProductViewModel 转换为 ProductExtendedViewModel。我应该怎么做?
这是我到目前为止没有成功的尝试:
viewModelExtended = (ViewModelExtended) viewModel;
我得到的提示是,在转换数字时,值必须小于无穷大
我不太擅长继承和转换,所以这对我来说都是全新的,所以请理解这个有点新手的问题。
谢谢
编辑
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; }
}
请您参考如下方法:
遗憾的是,在 C# 中,您不能从基类型转换为派生类型(“向下转换”),因为您将尝试生成信息(即 ExtendedName 应该有什么值?)。
你最好的选择是通过组合来做到这一点——在 ProductExtendedViewModel 上创建一个构造函数,它接受一个 ProductViewModel:
public class ProductExtendedViewModel : ProductViewModel
{
public ProductExtendedViewModel()
{
}
public ProductExtendedViewModel(ProductViewModel viewModel)
{
Name = viewModel.Name;
Product = viewModel.Product;
}
public string ExtendedName { get; set; }
}
然后你可以调用:
var productModel = new ProductViewModel {Name = product.Name, Product = product};
var derived = new ProductExtendedViewModel(productModel);
请注意,您仍然可以将 Derived 类型转换回它的基类型,因为这会丢失信息:
var basetype = (ProductViewModel)derived;
我认为“从数字 [...] 转换时”的“疑难解答提示”在这种情况下是转移注意力,只是对一般转换有帮助。
