开发者

What does it take to override a function in .NET

I was asked this in an interview today and I just can't figure it out. I was asked everything from beginning to advanced questions, but this one stuck out. I was describing inheritance and polymorphism and then this question came up. I have obviously never tried to override every method in a [C# / C++] class, but I wasn't aware there was something that was required in order to overr开发者_JAVA百科ide a particular method (.ToString, for example). Did I misinterpret the question or is there something required? And if so, what forces this requirement?


  • the base class must not be sealed
  • the method in the base class must be marked as virtual or abstract


The method you are overriding must be declared as virtual or abstract (and be in a non-sealed type). Otherwise, your only option is to hide it.


In C++ and C#, you have to declare the base-class function as virtual. Otherwise, a function in a derived class that has the same name and signature will hide the base class version.


The method that you want to override must be marked virtual or abstract.


If you understand polymorphism and inheritance, then I feel like maybe you're overthinking the question. I mean C# override is simply like this:

  public override double parentFunction() 
  {
     //child implementation
  }

... and the parent function must be delcared as virtual.

Without hearing the question verbatim, it's hard to say what the interviewer was looking for. My experience with interviewers is that they're just looking to make sure you understand the generalities, but who knows. I'd be curious to find out if you get the job : ) Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜