简体   繁体   English

在 C# 中创建通用列表类

[英]Create a Generic List Class in C#

I am working on some university material and I Have the following question我正在研究一些大学材料,我有以下问题

Design and implement a collection class dedicated to storing all objects of company documents as per the class hierarchy, inheriting from any .NET suitable collection class (eg the ArrayList class, or generic List).设计并实现一个集合类,专用于按照类层次结构存储公司文档的所有对象,继承自任何 .NET 合适的集合类(例如 ArrayList 类或通用列表)。 The collection is to implement a single method Page 2 of 5 GetDataOfAll() returning a string that concatenates data of all objects with suitable separators.该集合将实现一个方法 Page 2 of 5 GetDataOfAll() 返回一个字符串,该字符串使用合适的分隔符连接所有对象的数据。 (The method will later be used to display data in a suitable output placeholder) (该方法稍后将用于在合适的输出占位符中显示数据)

I wrote this:我是这样写的:

class MainList : List<Document>
{
    public string GetDataFormAll()
    {
        string text = null;
        foreach (Document data in MainList)
        {
            text += data.GetData() + "\n";
        }
        return text;
    }
}

Is this the correct way to implement this?这是实现这一点的正确方法吗?

foreach (Document data in MainList)

This is giving me an error it is telling me that MainList is not of the correct type.这给了我一个错误,它告诉我 MainList 的类型不正确。 How am I to implement this, please.请问我该如何实现。

You need to loop over the Document s in your own ( this ) collection.您需要循环遍历您自己( this )集合中的Document Since a List<T> is Enumerable<T> , you can simply write a foreach loop over the this :由于List<T>Enumerable<T> ,您可以简单地在this编写一个foreach循环:

public string GetDataFormAll() {
    string text = null;
    foreach (Document data in this) {
        text += data.GetData() + "\n";
    }
    return text;
}

(Yes, I code like an Egyptian ) (是的,我像埃及人一样编码)

Just another and shorter way, not necessarily better只是另一种更短的方式,不一定更好

public string GetDataFormAll()
{
    return string.Join("\n", this.Select(d => d.GetData());
}

And of course you can shorten it even more with .Select(GetData) syntax.当然,您可以使用.Select(GetData)语法进一步缩短它。

This will not add a \\n after the last element.不会在最后一个元素后添加\\n Depends on what you want.取决于你想要什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM