【问题标题】:How can refer base class instance?如何引用基类实例?
【发布时间】:2012-01-04 16:51:39
【问题描述】:

下面的例子,如何引用基类实例?

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

【问题讨论】:

  • 你会怎么做呢?您在 B 类的实例中没有 A 类的实例。
  • 如果这个例子在 Java 中,我可以使用 A.this.test 或 A.this.hello(),但是在 C# 中我该怎么做?除了传递 A 到 B 的引用?

标签: c#-2.0


【解决方案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.
        }
    }
}

【讨论】:

  • 谢谢,但是除了这种方式还有其他方式吗?
  • 据我所知,除了传递对对象 A 的引用之外别无他法。例如,C# 中的嵌套类的工作方式与它们在 C++ 中的工作方式不同..
【解决方案2】:

要清楚区分基类嵌套类,请参考下面的示例。


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
        }

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    相关资源
    最近更新 更多