试图访问方法中的嵌套类(两者都在同一个类中)。

时间:2015-04-23 12:20:13

标签: c#

我能够在另一个类

中访问show()方法
class program
{
    int num;
    string name;
    void store()
    {
        num = 1;
        name = "pc";
    }

    private class heai
    {
        public void show()
        {
            Console.WriteLine("hai");
        }
    }

    void display()
    {
        store();
        Console.WriteLine(num + name);
        //how to access show() here ??
    }
}

2 个答案:

答案 0 :(得分:0)

将班级的访问修饰符更改为public或protected。

答案 1 :(得分:0)

您需要拥有heai的实例才能访问show

像这样:

void display()
{
    var h = new heai();
    store();
    Console.WriteLine(num + name);
    h.show(); // here you are calling show on the instance of heai
}

顺便说一句:这与嵌套类无关。任何其他班级都是一样的。

如果您不想拥有heai的实例,可以show static

private class heai
{
    public static void show()
    {
        Console.WriteLine("hai");
    }
}

然后像这样称呼它:

void display()
{
    store();
    Console.WriteLine(num + name);
    heai.show(); // note: we are not accessing an instance of heai here, but the class itself
}