为什么动态变量的类型不像运行时方法的return类型?

Why the type of dynamic variable is not like the return type of the method at run time?

我有以下 C# 代码:

public class A
{
    public static A amethod()
    {
        return new C()
    }

}

public class C : A
{        
}

static void Main(string[] args)
{
    dynamic obj1 = A.amethod()
}

为什么在 运行 申请后 obj1 的类型是 C 而不是 A?

Why is the type of obj1 C and not A after running the application?

与你修改obj1的类型为C的原因相同:

A obj1 = A.amethod();

虽然 obj1 的静态已知类型是 A,但它的运行时类型是 C,因为那是 amethod() returns.

当您将 obj1 的类型更改为 dynamic 时,分配给它的值仍然是 C。然而,编译器保证不会用任何静态类型检查来打扰你,所以如果你这样做

obj1.SomeMethod();

代码会编译,但它会在运行时中断,除非您更改 C 以实现 SomeMethod()