无效的 Cast Exception 但构建工作正常

Invalid Cast Exception but build works fine

public class A
    {
        public void M1()
        {
            Console.Write("Print M1 of Class A");
        }
    }
public class B:A
{
    public void M2()
    {
        Console.Write("Print M2 of Class B");
    }
}

public class C : B
{
    public void M3()
    {
        Console.Write("Print M3 of Class C");

    }
}

在 main 方法中,我们创建如下对象:-

   A objA = new B();
    B objB = new C();
    A a = new A();
    C objC = (C)a;  /* this line throws runtime error System.InvalidCastException: 'Unable to cast object of type 'A' to type 'C'.'  but build works fine */

        objA.M1();
        objB.M1();
        objB.M2();
        objC.M1();
        objC.M2();
        objC.M3();

我无法首先将 C 直接转换为 A。因此尝试创建对象 A 然后显式转换它。智能感知将其视为有效代码并且构建也很好,但在控制台应用程序执行期间它抛出错误“无法将类型 'A' 的对象转换为类型 'C'。”

这是真的;您可以随时将 C 转换为 A,但唯一可以反过来执行的情况是,如果您已将 C 存储在类型为 A 的变量中。编译器允许您这样做,因为 C 是 A 的后裔,因此类型 A 的变量能够保存类型 C 的实例。因此,您可以合法地将 C 存储在 A 中,然后进行转换以使其恢复为 C:

A reallyC = new C();
C gotBack = (C)reallyC;

编译器不会仔细检查您之前所做的事情;它不会看到这样的代码:

A reallyA = new A();
C willFail = (C)reallyA;

然后说“嘿;你已经在 reallyA 中存储了一个 A,它不能转换为 C”。它只是看到你试图将 reallyA 转换为 C,并认为“它可能是 C,因为 C 是 B 是 A,所以它们是相关的。我相信开发人员知道他们在做什么,我会允许的

嗯,a 是 (base) 类型 A 并且不能转换为 C,因为 CA 派生的 。反过来是可能的:derived class C 的对象 c 可以转换为 base class A:

 C c = new C(); 
 A objA = (A) c;

通常我们可以尝试is的帮助下施法:

if (a is C objC) {
  // a can be cast to C, objC now holds the result of the cast  
  objC.M3();
}
else {
  // the cast is impossible
}