简体   繁体   English

如何创建可以迭代的类的集合?

[英]How to create a collection of classes that can be iterated over?

I have a series of properties for an object which are themselves a class: 我有一个对象的一系列属性,这些属性本身就是一个类:

private ClassThing Thing1;
private ClassThing Thing2;
private ClassThing Thing3;

private class ClassThing
{
    public string Name;
    public int Foos;
}

In some areas I need to be able to access each property specifically, for example: 在某些区域,我需要能够专门访问每个属性,例如:

label1.Text = Thing1.Name;

However, it is also desirable to create a foreach loop to access each one, like this: 但是,也希望创建一个foreach循环来访问每个循环,如下所示:

string CombinedString;
foreach(ClassThing Thing in SomeCollection)
{
    CombinedString += Thing.Name;
}

The end result must be XML serializable. 最终结果必须是XML可序列化的。 These examples are very basic, but I hope they more easily demonstrate my need. 这些示例非常基础,但我希望它们能更轻松地说明我的需求。

I tried creating a dictionary of these properties instead, but a dictionary is not XML serializable. 我尝试创建这些属性的字典,但是字典无法XML序列化。 I'd like to simply make all of these properties members of a class that itself can be iterated over, but I'm not sure how. 我只想简单地使一个类的所有这些属性成员都可以迭代,但是我不确定如何做。

Can anyone point me in the right direction? 谁能指出我正确的方向?

I hope this clarifies some things for you, since i am not entirely sure i understand your question. 我希望这可以为您澄清一些事情,因为我不确定我是否理解您的问题。

//many normal classes can be made xml serializable by adding [Serializable] at the top of the class
[Serializable]
private class ClassThing
{
    public string Name { get; set; }
    public int Foos { get; set; }
}

//here we create the objects so you can access them later individually
ClassThing thing1 = new ClassThing { Name = "name1", Foos = 1 };
ClassThing thing2 = new ClassThing { Name = "name2", Foos = 2 };
ClassThing thing3 = new ClassThing { Name = "name3", Foos = 3 };

//this is an example of putting them in a list so you can iterate through them later.
List<ClassThing> listOfThings = new List<ClassThing>();
listOfThings.Add(thing1);
listOfThings.Add(thing2);
listOfThings.Add(thing3);

//iteration example
string combined = string.Empty;
foreach (ClassThing thing in listOfThings)
{
    combined += thing.Name;
}

//you could also have created them directly in the list, if you didnt need to have a reference for them individually, like this:
listOfThings.Add(new ClassThing { Name = "name4", Foos = 4 });

//and more advanced concepts like linq can also help you aggregate your list to make the combined string. the foreach makes the code more readable though. this gives the same result as the foreach above, ignore it if it confuses you :)
string combined = listOfThings.Aggregate(string.Empty, (current, thing) => current + thing.Name);

//Here is an example of how you could serialize the list of ClassThing objects into a file:
using (FileStream fileStream = new FileStream("classthings.xml", FileMode.Create))
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<ClassThing>));
    xmlSerializer.Serialize(fileStream, listOfThings);
}

To be able to serialize the objects using this method, they cannot contain a constructor, which is why we use the new ClassThing{Name="",Foos=0} way of creating them. 为了能够使用此方法序列化对象,它们不能包含构造函数,这就是为什么我们使用new ClassThing{Name="",Foos=0}方式创建它们的原因。

You're looking for an implementation of the IEnumerable interface. 您正在寻找IEnumerable接口的实现。 See this link for a quick description of how to implement it. 请参阅此链接以快速了解如何实现它。

    class MyClass
{
    private ClassThing Thing1;
    private ClassThing Thing2;
    private ClassThing Thing3;

    internal IEnumerable<ClassThing> GetThings()
    {
            yield return Thing1;
            yield return Thing2;
            yield return Thing3;
    }
    void Test()
    {
        foreach(var thing in this.GetThings())
        {
            //use thing
        }
    }
}
public List<ClassThing> Things = new List<ClassThing>();

然后,您可以运行foreach了。

暂无
暂无

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

相关问题 如何检查字典/集合是否可以迭代? - How to check that a dictionary / collection can be iterated over? foreach如何知道迭代集合被修改了? - How can foreach know the iterated collection was modified? C#Parallel - 将项目添加到正在迭代的集合中,还是等效的? - C# Parallel - Adding items to the collection being iterated over, or equivalent? 如何在传递给视图以作为有序列表进行迭代的 ViewModel 集合中获取 jQuery 可选对象的值? - How can I get the value of a jQuery selectable object in a ViewModel collection I passed to my view to be iterated through as an ordered list? 如何在C#中创建要在循环中迭代的类的列表 - How can I create a list of classes in C# to iterate over in a loop 如何制作可以迭代的ApplicationUser类型的列表? - How to make a list of ApplicationUser type that could be iterated over? 如何限制在foreach循环中迭代的元素数量? - How do I limit the number of elements iterated over in a foreach loop? 如何在foreach循环中对迭代的元素进行分段 - How do I segment the elements iterated over in a foreach loop 为什么我不能用 linq 迭代可以用 foreach 迭代的东西? - Why can I not iterate over something with linq that can be iterated over with foreach? 如果我有一个类的集合,如何返回所有类的单个属性的集合? - If I have a collection of classes how can I return a collection of a single attribute of all the classes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM