首页 > 解决方案 > C#:如何使用循环创建新的结构对象

问题描述

如何通过循环创建新的结构对象。Foreach 通过列表的元素例如?

这是我的结构:

public struct TestStruct
{
    public int value1;
    public int value2;
    public List<string> firststructlist;

    public TestStruct(int bab, int bob)
    {
        value1 = bab;
        value2 = bob;
        firststructlist = new List<string>();
     }
     
    public void Add(string value)
    {
        if (firststructlist == null)
            firststructlist = new List<string>();
        firststructlist.Add(value);
    }
}

看起来不错,我可以“手动”创建新对象

TestStruct second = new TestStruct(1, 2);
second.value1 = 8;
second.value2 = 9;
second.firststructlist.Add("panapinom");
second.firststructlist.Add("zsakfos");

但在运行时未能通过循环完成。我想象过这样的事情(这当然行不通):

foreach (string something in anything)
{
    TestStruct "something" = new TestStruct(1, 2);
    // new TestStruct for all "something" in the list
}`enter code here`

请帮忙!

标签: c#struct

解决方案


推荐阅读