In .NET can a class have virtual constructor?

前端 未结 7 1764
别跟我提以往
别跟我提以往 2020-12-15 04:35

Can a class have virtual constructor??

If yes, why it is required?

7条回答
  •  失恋的感觉
    2020-12-15 05:11

    A virtual method is by definition a method which is dispatched based on runtime type analysis of the receiver, not the compile-time static type analysis of the receiver.

    A constructor is a method called when a new instance of a particular type is created.

    Since the runtime type of a newly created object is always the same (*) as its compile-time type, there is no need for virtual constructors: the runtime dispatch would always choose the same method as the static dispatch, so why bother making a difference?

    (*) This is not entirely true; there are scenarios involving COM interop in which the runtime type of a construction is not the compile-time type. Many things are weird in the world of legacy interop code.

提交回复
热议问题