gpt4 book ai didi

c# - 无法通过嵌套类型访问外部类型的非静态成员

转载 作者:太空狗 更新时间:2023-10-29 18:06:44 29 4
gpt4 key购买 nike

我有错误

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

使用这样的代码(简化):

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 类,但我需要在外部使用此方法。

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

提前致谢。

最佳答案

问题是嵌套类不是派生类,所以外部类中的方法不是继承

一些选项是

  1. 使方法静态:

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

    public static int OtherMethod()
    {
    return 123;
    }
    }
  2. 使用继承而不是嵌套类:

    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();
    }
    }
  3. 创建 Neuro 实例:

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

    public int OtherMethod()
    {
    return 123;
    }
    }

关于c# - 无法通过嵌套类型访问外部类型的非静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16320935/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com