《illustrate c#2008》:

Figure 7-1 shows an instance of each of the classes. Class SomeClass, on the left, has one field and one method. Class OtherClass, on the right, is derived from SomeClass and contains an additional field and an additional method.

 

 

图7-1shows 每一个类的instance,也就是someclass父类、otherclass派生类各自的instance。一个名字叫SomeClass的类,在左边放着,这个名字叫SomeClass的类一不小心怀有一个field和一个mehtod。一个名字叫做OtherClass的类,在右边放着,derived from 一个名字叫SomeClass的类。这个名字叫做OtherClass的类一不小心怀有另外一个field和另外一个method。

 

Accessing the Inherited Members

进入继承成员的方法(访问继承的成员)


Inherited members are accessed just as if they had been declared in the derived class itself. (Inherited constructors are a bit different—I’ll cover them later in the chapter.) For example, the following code declares classes SomeClass and OtherClass, which were shown in Figure 7-1.

继承的成员可以被 accessed, 好像他们已经被声明在派生类中一样(继承构造函数?Inherited constructors稍微有点不同-我在后面的章节会cover)。例如,下面的代码声明了类SomeClass and OtherClass, which were shown in Figure 7-1.


The code shows that all four members of OtherClass can be seamlessly accessed, regardless of
whether they are declared in the base class or the derived class.
• Main creates an object of derived class OtherClass.
• The next two lines in Main call Method1 in the base class, using Field1 from the base class,
and then Field2 from the derived class.
• The subsequent two lines in Main call Method2 in the derived class, again using Field1 from the base class and then Field2 from the derived class.

代码显示了4个成员,这个4个成员在OtherClass中。这4个在OtherClass中的成员能够被seamlessly访问,而不管他们是否在基类中被声明过,也不管他们在派生类中是否被声明过。

--Main 创造了 派生类OtherClass的一个对象

--Main接下去下的2行:编译器第一个碰见的叫做Method1,这个Method1存在于基类,然后使用Field1,这个Field1存在于基类,然后使用 Field2,这个 Field2存在于派生类。

--随后的2行:编译器第一个碰见的叫做Method2,这个 Method2存在于派生类。同样又使用Field1,这个Field1来自基类,然后同样又使用Field2,这个Field2来自派生类。

 

 

class SomeClass {       // Base class
  public string Field1 = "base class field";
  public void Method1( string value ) {
  Console.WriteLine("Base class -- Method1: {0}", value);
}
}
class OtherClass: SomeClass {     // Derived class
  public string Field2 = "derived class field";
  public void Method2( string value ) {
  Console.WriteLine("Derived class -- Method2: {0}", value);
}
}
class Program {
  static void Main() {
     OtherClass oc = new OtherClass();
     oc.Method1( oc.Field1 ); // Base method with base field
     oc.Method1( oc.Field2 ); // Base method with derived field
     oc.Method2( oc.Field1 ); // Derived method with base field
       oc.Method2( oc.Field2 ); // Derived method with derived field
}
}

This code produces the following output:

这些代码产生出produces以下结果:
Base class -- Method1: base class field
Base class -- Method1: derived class field
Derived class -- Method2: base class field
Derived class -- Method2: derived class field

 

 

 

 

 

 

posted on 2010-08-22 01:34  菜刀大侠  阅读(245)  评论(0编辑  收藏  举报