方法是否重载多态在C#中的早期绑定?

Nic*_*kis 3 c# polymorphism early-binding

在C#中,如果我有

public class BaseClass
{
    //BaseClass implementation
}

public class Derived : BaseClass
{
    //Derived implementation
}

public class AnotherClass
{
    AnotherClass(BaseClass baseClass)
    {
        //Some code
    }

    AnotherClass(Derived derived) : this(derived as BaseClass)
    {
        //Some more code
    }
}
Run Code Online (Sandbox Code Playgroud)

然后做:

BaseClass    baseVariable    = new Derived();
AnotherClass anotherVariable = new AnotherClass(baseVariable);
Run Code Online (Sandbox Code Playgroud)

这将导致早期绑定,调用该AnotherClass(BaseClass)方法.

相反,如果我使用dynamic关键字转换它- 或者使用动态实例化变量然后将其作为构造函数参数传递,AnotherClass(Derived)则将调用它:

BaseClass    baseVariable    = new Derived();
//This will instantiate it using the AnotherClass(Derived)
AnotherClass anotherVariable = new AnotherClass(baseVariable as dynamic);
Run Code Online (Sandbox Code Playgroud)

方法是否在C#中进行早期绑定(在编译时评估)?这意味着,有没有其他方式或技巧 确定对其他类构造函数的主要派生调用在不使用dynamic或反射的情况下应用构造函数的调用,该构造函数将大部分派生类类型作为参数?

Jon*_*eet 11

C#中的绑定时间取决于绑定是否涉及dynamic.正如您所见,如果您使用,dynamic您将获得执行时重载解析; 如果不这样做,您将获得编译时重载解析.

请注意,即使重载解析涉及动态类型,它仍将使用编译时已知的信息 - 只有类型的表达式dynamic使用执行时类型.例子:

using System;

class Test
{
    static void Main()
    {
        object x = "abc";
        dynamic y = 10;

        Foo(x, y); // Prints Foo(object,int)
    }

    static void Foo(object x, int y)
    {
        Console.WriteLine("Foo(object,int)");
    }

    static void Foo(string x, int y)
    {
        Console.WriteLine("Foo(string,int)");
    }
}
Run Code Online (Sandbox Code Playgroud)

如果更改声明的xto 类型dynamic,执行时类型将是相关的(并将打印Foo(string,int)).

当然,这只是重载决策- 覆盖总是在执行时确定,除非您使用非虚拟调用(调用非虚方法或使用base.Foo(...).

  • 当Jon Skeet抛出异常时,没有什么可以捕获它. (2认同)