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

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

问题描述

我有错误

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

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

像这样的代码(简化):

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.

我是一个客观的编程新手.

Im kind of objective programming newbie.

提前致谢.

推荐答案

问题在于嵌套类不是派生类,所以外层类中的方法是不是继承.

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

有些选项是

  1. 使方法static:

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(); 
        }
    }
    

  • 创建一个Neuro的实例:

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

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

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