Permanently cast derived class to base

前端 未结 6 1546
慢半拍i
慢半拍i 2020-12-09 16:19
Class A { }
Class B : A { }

B ItemB = new B();
A ItemA = (A)B;

Console.WriteLine(ItemA.GetType().FullName);

Is it possible to do something like a

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 17:15

    (this is probably obvious, but...)

    re: the accepted answer by @Ani:

    If you still want to do this; you could write a method that manually constructs an A from a B by newing up an A and then copying data over. This might exist as a ToA() instance-method on B.

    Or use Automapper to copy the data back:

    Mapper.CreateMap();
    // ...later...
    var wipedInstance = Mapper.Map(instanceOfChildClass);
    

    then wipedInstance.GetType() would be typeof(BaseClass)

提交回复
热议问题