2011-08-27 87 views
0

以下示例中,我如何引用基类实例?如何引用基类实例?

public class A 
{ 
    public string test; 
    public A() 
    { 
     B b = new B(); 
     test = "I am A class of test."; 
    } 

    public void hello() 
    { 
     MessageBox.Show("I am A class of hello."); 
    } 

    class B 
    { 
     public B() 
     { 
      //Here... 
      //How can I get A class of test and call A class of hello method 
      //base.test or base.hello() are not working. 
     } 
    } 
} 
+0

如果这个例子在Java中,我可以使用A.this.test或A.this.hello(),但是在C#中我该怎么办?除了传递A到B的引用? – Jasper

+0

你会怎么做?您在B类的实例中没有获得类A的实例。 – Carsten

回答

1

你得A的引用传递给B.

你可以做到这一点

的一种方法如下:

public class A 
{ 
    string name = "Class A"; 

    public A() 
    { 
     var b = new B(this); 
    } 

    class B 
    { 
     public B(A a) 
     { 
      a.name.Dump(); // Write out the property of a.name to some stream. 
     } 
    } 
} 
+0

谢谢,但除此之外,还有其他方法吗? – Jasper

+0

据我所知除了传递对象A的引用没有其他的方式。在C#中的嵌套类不像在C++中那样工作..例如.. –

+0

好吧,谢谢你的回答。 – Jasper

1

基类和明确区分嵌套类,请参考下面的例子。


namespace Example 
{ 
    class A 
    { 
     string Name = "test"; // access restricted only to this class 
     public string Type; // global access 
     internal string Access; // within defining namespace 
     protected string Code; // this class and subclass 

     // When you create a nested class like C, you can create instances of C within this class(A). 

     C c = new C(); 

     class C 
     { 
      string name; 
      public C() 
      { 
       //this is a nested class and you cannot call A as its base 
       name = "test success"; 
      } 
     } 
    } 

    class B : A 
    { 
     public string Type { get { return base.Type; } set { base.Type = value; } } // You can use base when you hide a base class member 
     public B() 
     { 
      Type = "test"; 
      Code = "nothing"; 
      Access = "success"; 
      //Cannot Access 'Name' Here as it is private 
     } 

    } 
}