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

尼克·L。

在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
    }
}

然后执行:

BaseClass    baseVariable    = new Derived();
AnotherClass anotherVariable = new AnotherClass(baseVariable);

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

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

BaseClass    baseVariable    = new Derived();
//This will instantiate it using the AnotherClass(Derived)
AnotherClass anotherVariable = new AnotherClass(baseVariable as dynamic);

方法是否在C#中重载了早期绑定(在编译时评估)?意思是还有其他方法或技巧 确定对其他类构造函数的大部分派生调用在我的情况下不使用dynamic或反射来应用将大部分派生类类型作为参数的构造函数的调用

乔恩·斯基特

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)");
    }
}

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章