An interesting question about C # Polymorphism

Source: Internet
Author: User
The content posted in the rainst Forum is very simple but falls into a trap.

1 class Program
2 {
3 static void main (string [] ARGs)
4 {
5
6 var T = new C ();
7 T. Say ();
8 (T as B). Say ();
9 (T as a). Say ();
10 console. Readline ();
11}
12}
13
14 Class
15 {
16 private int x = 1;
17 Public Virtual void say ()
18 {
19 console. writeline (X. tostring ());
20}
21}
22
23
24 Class B:
25 {
26 private int x = 2;
27 public new void say ()
28 {
29 console. writeline (X. tostring ());
30}
31
32}
33
34 Class C: B
35 {
36}

What is output? Do not compile

Change the T variable declaration to a T = new C ();

What is output now?

Further, change Class B

Class B:
{
Private int x = 2;

Public override void say ()
{
Console. writeline (X. tostring ());
}

}

What about now?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.