gpt4 book ai didi

c# - 方法重载多态性是否在 C# 中早期绑定(bind)?

转载 作者:行者123 更新时间:2023-11-30 13:26:02 25 4
gpt4 key购买 nike

在 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);

这将导致早期绑定(bind),调用 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# 中重载早期绑定(bind)(在编译时求值)?这意味着,是否有任何其他方法或技巧 来确定对其他类构造函数的大部分派(dispatch)生调用 以应用构造函数的调用,在我的情况下,该调用将大部分派(dispatch)生类类型作为参数,而无需使用动态还是反射?

最佳答案

C# 中的绑定(bind)时间取决于绑定(bind)是否涉及动态。如您所见,如果您使用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)");
}
}

如果您将 x 的声明类型更改为 dynamic那么 执行时类型将是相关的(并且它将打印 Foo(string,int)).

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

关于c# - 方法重载多态性是否在 C# 中早期绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34271199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com