What is Shadowing?

2019-01-03 05:57发布

In C# what does the term shadowing mean? I have read this link but didn't fully understand it.

11条回答
对你真心纯属浪费
2楼-- · 2019-01-03 06:25

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

  • Shadowing: The method called depends on the type of the reference at the point the call is made
  • Overriding: The method called depends on the type of the object at the point the call is made.
查看更多
一夜七次
3楼-- · 2019-01-03 06:26
  • Overriding : redefining an existing method on a base class
  • Shadowing : creating an entirely new method with the same signature as one in a base class
查看更多
虎瘦雄心在
4楼-- · 2019-01-03 06:27

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.

查看更多
倾城 Initia
5楼-- · 2019-01-03 06:27
 private static int x = 10;


static void Main(string[] args)
    { int x = 20;
        if (Program.x == 10)
        {
            Console.WriteLine(Program.x);
        }
        Console.WriteLine(x);}

Output:

10 20

查看更多
我只想做你的唯一
6楼-- · 2019-01-03 06:33

Shadowing hides a method in a base class. Using the example in the question you linked:

class A 
{
   public int Foo(){ return 5;}
   public virtual int Bar(){return 5;}
}
class B : A
{
   public new int Foo() { return 1;}
   public override int Bar() {return 1;}
}

Class B overrides the virtual method Bar. It hides (shadows) the non-virtual method Foo. 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 class B, you would get this compiler warning:

'test.B.Foo()' hides inherited member 'test.A.Foo()'. Use the new keyword if hiding was intended.
查看更多
\"骚年 ilove
7楼-- · 2019-01-03 06:43

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

Base B=new Child()

B.VirtualMethod() -> Calls Child class method

B.NonVirtualMethod() -> Calls Base class method

查看更多
登录 后发表回答