开发者

How can I create List<custom Class> when custom Class contains List<T> it self?

开发者 https://www.devze.com 2023-04-11 15:10 出处:网络
I\'m trying to create a Class with List of Lists, but can\'t get it to work: public class Structure { public List<int> variable1 = new List<int>();

I'm trying to create a Class with List of Lists, but can't get it to work:

public class Structure
{
    public List<int> variable1 = new List<int>();
    public double variable2 { get; set; }
}

public class StructureHolder
{
    public List<Structure> variable3 = new List<Structure>();
    public void InitLists()
    {
        variable3.Capacity = 1;
        variable3[0].variable1.开发者_如何学JAVACapacity = 20;
    }
    public void SomeMethod()
    {
        //Perform operations on values storred in variable3[i].variable1
    }
}

Now when I create SomeVariable of class StructureHolder and try to access SomeVariable.variable3[0].variable2 I get out of range error.

Edit1: Fixed that, but I still get out of range exception:

variable3.Capacity = 1;
variable3.Add(new Structure());
variable3[0].variable1.Capacity = 20;
variable3[0].variable1[0] = 123;    //out off range error


But the list in StructureHolder doesn't contain any elements yet. You have to add eg.

variable3.Capacity = 1;
variable3.Add(new Structure());
variable3[0].variable1.Capacity = 20;


It's because your are trying to access empty List. You just initialize the list

public List<Structure> variable3 = new List<Structure>();

but never adds some elements to it:

variable3.Add(...);

So, you need to add item first before accessing it:

variable3.Add(new Structure()); // adding item
variable3[0].variable2 = 100d; // accessing just added element field
0

精彩评论

暂无评论...
验证码 换一张
取 消