Как можно ссылаться на экземпляр базового класса? - PullRequest
0 голосов
/ 27 августа 2011

В следующем примере, как мне обратиться к экземпляру базового класса?

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.
        }
    }
}

Ответы [ 2 ]

1 голос
/ 04 января 2012

Чтобы четко различать базовый класс и вложенный класс , см. Приведенный ниже пример.


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
        }

    }
}

1 голос
/ 27 августа 2011

Вы должны передать ссылку 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.
        }
    }
}
...