在 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
关键字转换它 - 或使用动态实例化一个变量,然后将其作为构造函数参数传递,AnotherClass(Derived)
则将调用:
BaseClass baseVariable = new Derived();
//This will instantiate it using the AnotherClass(Derived)
AnotherClass anotherVariable = new AnotherClass(baseVariable as dynamic);
方法是否在 C# 中重载早期绑定(在编译时评估)?那个意思,有没有其他的方法或者技巧确定对另一个类构造函数的主要派生调用在不使用dynamic
或反射的情况下,应用将主要派生类类型作为参数的构造函数的调用?