c#:将基本类型转换为派生类型

时间:2020-03-03 12:55:29

标签: c#

我正在C#中编写一个应用程序,尝试将CustomerSupplier转换为CustomerSupplierViewModel时遇到运行时错误。

然后,此类的定义为:

    public class CustomerSupplier
    {
        public string code;
        // … the rest of the structure is here … 
    }

    // the next class is just this… 
    public class CustomerSupplierViewModel : CustomerSupplier
    {

    }

但是我什么时候做:

   CustomerSupplierViewModel vm = (CustomerSupplierViewModel) data;

我收到运行时错误(无效转换):System.InvalidCastException: 'Unable to cast object of type 'MyProgram.Models.CustomerSupplier' to type 'MyProgram.Models.ViewModels.CustomerSupplierViewModel'.'

我试图在视图模型中创建一个构造函数,但这也没有得到结果:

        public CustomerSupplierViewModel(CustomerSupplier d) : base(d) { }

这需要CustomerSupplier中的构造函数,这会很长……

在不摆脱视图模型的前提下,我该如何进行投射。我认为这应该很容易...

0 个答案:

没有答案
相关问题