C#:抽象列表<string>

C#: Abstract List<string>

C#: 我想用一种适用于字符串列表的方法编写抽象 class。该列表尚未在此 class 中实施。 然后我想写另一个 classes 继承抽象 class 并实现 List of strings.

class AbstractClass 
{
    protected abstract List<string> myList; // To be implemented in a child class
    void ShowList()
    {
        foreach (string member in myList) 
        {
            Console.WriteLine(member);
        }
    }
}

class HelloWorld : AbstractClass
{
    new private List<String> myList = new List<string>()
    {
        "Hello", "World"
    }; 
}

现在 C# 告诉我 "The modifier abstract is not valid on fields. Try using a property instead." 我似乎没有得到大局。我只想要一个 placeholder/reference 到我的基本父级 class 中的列表。这是怎么做到的?

您的代码有几个问题。这将修复它们:

abstract class AbstractClass
{
    protected abstract List<string> MyList { get; set; } // To be implemented in a child class

    void ShowList()
    {
        foreach (string member in MyList)
        {
            Console.WriteLine(member);
        }
    }
}

class HelloWorld : AbstractClass
{
    protected override List<String> MyList { get; set; } = new List<string>()
    {
        "Hello", "World"
    };
}

问题:

  • 摘要 class 应使用 abstract class;
  • 声明
  • 如果要在派生的中覆盖其功能,则需要使用属性或方法 class;
  • 您使用的是 new 关键字。如果您想在派生 class 中派生某些东西,请不要这样做!请改用 override