In .NET can a class have virtual constructor?

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

Can a class have virtual constructor??

If yes, why it is required?

相关标签:
7条回答
  • 2020-12-15 05:30

    no, a class cannot have a virtual constructor.

    It doesn't make sense to have a virtual constructor. The order in which objects are constructed in C# is by constructing derived classes first, so the derived constructor is always called since the class you want to call is well known at the time of construction.

    The other thing is, if you actually type this code out, you can quickly see that it makes very little sense at all

    If you had:

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

    and then

    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()
        {
        }
    }
    
    0 讨论(0)
提交回复
热议问题