代码之家  ›  专栏  ›  技术社区  ›  Ram

在.NET中,类可以有虚拟构造函数吗?

  •  21
  • Ram  · 技术社区  · 15 年前

    一个类能有虚拟构造函数吗??

    7 回复  |  直到 15 年前
        1
  •  24
  •   lomaxx    15 年前

    不,类不能有虚拟构造函数。

    另一件事是,如果你真的把这段代码打出来,你很快就会发现它毫无意义

    如果你有:

    public class BaseClass 
    {
        public virtual BaseClass()
        {
        }
    }
    

    public class InheritedClass : BaseClass
    {
        //overrides baseclass constructor but why would you do this given that the     
        //constructor is always going to be called anyway??
        public override InheritedClass()
        {
        }
    }
    
        2
  •  13
  •   Eric Lippert    15 年前

    根据定义,虚拟方法是

    构造函数是在创建特定类型的新实例时调用的方法。

    因为新创建的对象的运行时类型是 总是一样的 (*)作为它的编译时类型,不需要虚拟构造函数:运行时调度总是选择与静态调度相同的方法,那么为什么还要费心去做一些改变呢?

        3
  •  5
  •   Cumbayah    15 年前

    不是直接的,但是经典的GangofFour模式工厂方法通过将实例化推迟到子类来实现某种虚拟构造函数。

        4
  •  2
  •   DanDan    15 年前

    当您使用工厂模式时,可以将其描述为具有类似于虚拟构造函数的行为。想象一下这个场景:

    class AnimalFactory
    {
        virtual Animal CreateAnimal( return new Animal("Cow"); );
    }
    

    class DogFactory : AnimnalFactory
    {
        override Animal CreateAnimal( return new Animal("Dog"); );
    }
    

        5
  •  0
  •   teukkam    15 年前

        6
  •  0
  •   Damian Leszczyński - Vash    15 年前

        7
  •  0
  •   Just another metaprogrammer    15 年前

    仅供参考,当人们要求虚拟构造器一个非常好的模式,看看是 InversionOfControl

    IoC是OO兑现承诺的动力。