Csharp/CSharp Tutorial/Class/Name Hiding

Материал из .Net Framework эксперт
Версия от 12:16, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

An example of inheritance-related name hiding.

using System; 
 
class BaseClass { 
  public int i = 0; 
} 
 
// Create a derived class. 
class DerivedClass : BaseClass { 
  new int i; // this i hides the i in BaseClass 
 
  public DerivedClass(int b) { 
    i = b; // i in DerivedClass 
  } 
 
  public void show() { 
    Console.WriteLine("i in derived class: " + i); 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    DerivedClass ob = new DerivedClass(2); 
 
    ob.show(); 
  } 
}
i in derived class: 2

Call a hidden method

using System; 
 
class BaseClass { 
  public int i = 0; 
 
  // show() in BaseClass 
  public void show() { 
    Console.WriteLine("i in base class: " + i); 
  } 
} 
 
// Create a derived class. 
class DerivedClass : BaseClass { 
  new int i; // this i hides the i in BaseClass 
 
  public DerivedClass(int a, int b) { 
    base.i = a; // this uncovers the i in BaseClass 
    i = b; // i in DerivedClass 
  } 
  // This hides show() in BaseClass. Notice the use of new. 
  new public void show() { 
    base.show(); // this calls show() in BaseClass 
 
    // this displays the i in DerivedClass 
    Console.WriteLine("i in derived class: " + i); 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    DerivedClass ob = new DerivedClass(1, 2); 
 
    ob.show(); 
  } 
}
i in base class: 1
i in derived class: 2

Using base to overcome name hiding.

using System; 
 
class BaseClass { 
  public int i = 0; 
} 
 
// Create a derived class. 
class DerivedClass : BaseClass { 
  new int i; // this i hides the i in BaseClass 
 
  public DerivedClass(int a, int b) { 
    base.i = a; // this uncovers the i in BaseClass 
    i = b; // i in DerivedClass 
  } 
 
  public void show() { 
    // this displays the i in BaseClass. 
    Console.WriteLine("i in base class: " + base.i); 
 
    // this displays the i in DerivedClass 
    Console.WriteLine("i in derived class: " + i); 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    DerivedClass ob = new DerivedClass(1, 2); 
 
    ob.show(); 
  } 
}
i in base class: 1
i in derived class: 2