In C# what does the term shadowing mean? I have read this link but didn't fully understand it.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Expanding on Kent's correct answer
When disambiguating when which method will be called, I like to think of shadowing vs. overriding with the following
Here's an MSDN article on Shadowing. The language examples are in Visual Basic (unfortunately there is no equivalent C# page on MSDN), but it deals generally with the concepts and hopefully should help you understand anyway.
Edit: Seems like there is a C# article on shadowing, except that it's called hiding in C#. Also, this page offers a good overview.
Output:
10 20
Shadowing hides a method in a base class. Using the example in the question you linked:
Class
B
overrides the virtual methodBar
. It hides (shadows) the non-virtual methodFoo
. Override uses the override keyword. Shadowing is done with the new keyword.In the code above, if you didn't use the new keyword when defining the
Foo
method in classB
, you would get this compiler warning:If you want to hide Base class method , Use override in base [virtual method in base]
if you want to hide Child class method , Use new in base [nonvirtual method in base]->shadow
B.VirtualMethod()
-> Calls Child class methodB.NonVirtualMethod()
-> Calls Base class method