通过嵌套类不能访问外部类的非静态成员 [英] Cannot access a non-static member of outer type via nested type

查看:781
本文介绍了通过嵌套类不能访问外部类的非静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有误差

无法访问Project.Neuro外类型的非静态成员通过
  嵌套式Project.Neuro.Net

Cannot access a non-static member of outer type 'Project.Neuro' via nested type 'Project.Neuro.Net'

与code像这样(简体):

with code like this (simplified):

class Neuro
{
    public class Net
    {
        public void SomeMethod()
        {
            int x = OtherMethod(); // error is here
        }
    }

    public int OtherMethod() // its outside Neuro.Net class
    {
        return 123;  
    }
}

我可以将有问题的方法Neuro.Net类,但我需要外界的这种方法。

I can move problematic method to Neuro.Net class, but I need this method outside.

林样的目标规划新手。

先谢谢了。

推荐答案

问题是,嵌套的类不是的导出的类,所以在外部类中的方法不是的继承

The problem is that nested classes are not derived classes, so the methods in the outer class are not inherited.

某些选项


  1. 请方法静态

class Neuro
{
    public class Net
    {
        public void SomeMethod()
        {
            int x = Neuro.OtherMethod(); 
        }
    }

    public static int OtherMethod() 
    {
        return 123;  
    }
}


  • 使用继承代替嵌套类:

  • Use inheritance instead of nesting classes:

    public class Neuro  // Neuro has to be public in order to have a public class inherit from it.
    {
        public static int OtherMethod() 
        {
            return 123;  
        }
    }
    
    public class Net : Neuro
    {
        public void SomeMethod()
        {
            int x = OtherMethod(); 
        }
    }
    


  • 创建神经的一个实例:

    class Neuro
    {
        public class Net
        {
            public void SomeMethod()
            {
                Neuro n = new Neuro();
                int x = n.OtherMethod(); 
            }
        }
    
        public int OtherMethod() 
        {
            return 123;  
        }
    }
    


  • 这篇关于通过嵌套类不能访问外部类的非静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆