【问题标题】:Using a method made in a parent class in a child class c#在子类c#中使用父类中的方法
【发布时间】:2021-05-21 11:26:25
【问题描述】:

我有两个班级:

    class ClassOne 
{
    Stack<int> s = new Stack<int>();
    public Stack<int> MakeStack()
    {
        for (int i = 0; i < 10; i++)
        {
            
            s.Push(i);
        }
        return s;
    }

}


class ClassTwo:ClassOne
{
    Stack<int> st = MakeStack();
    int[] array = new int[2];
    private int[] GetFirstTwo()
    {
        for (int i = 0; i < 1; i++)
        {
            array[i] = st.Pop();
        }
        
        return array;
    }

}

但是当我尝试在子类中使用 MakeStack 时,它会给出错误“字段初始化程序无法引用非静态字段、方法或属性 'ClassOne.MakeStack'。

我知道一个解决方法是在父类中做所有事情,并在我需要覆盖不同子类中的东西时将其抽象化,但希望有一种方法可以在没有所有这些的情况下做我需要的事情,因为我做不到调查时发现任何有用的东西。

【问题讨论】:

  • 你指的是 MakeDeck。我们没有看到该代码。
  • MakeDeck 指的是我的实际代码,而不是我写的这个虚拟代码。现在已经编辑了

标签: c# oop inheritance


【解决方案1】:

使用构造函数:

class ClassTwo : ClassOne
{
    Stack<int> st;
    
    ClassTwo()
    {
        st = MakeStack();
    }
    // ...
}

为什么在这里查看示例:Understanding C# field initialization requirements

【讨论】:

    猜你喜欢
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多