Permanently cast derived class to base

前端 未结 6 1547
慢半拍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:14

    No, you can't force an instance of a child type to report that it's type name is the base type.

    Note that when you are using the ItemA variable pointing to the instance of class B, you can only access the fields and methods defined in class A using the ItemA variable. There are very few places where the fact that ItemA points to an instance of something other than class A can actually be observed - virtual methods overridden in the child classes is one case, and operations on the runtime type itself, such as GetType().

    If you're asking this question because some piece of code is failing when you send it an instance of class B when it is expecting an instance of class A, it sounds like you should be taking a closer look at that code to see what it's doing wrong. If it's testing GetType.LastName, then it's broken and braindead. If it's testing x IS A then passing an instance of B will pass and everything should be fine.

提交回复
热议问题