【问题标题】:dynamic generating variable in C#C#中的动态生成变量
【发布时间】:2015-08-23 11:34:22
【问题描述】:

我的代码需要根据我的文本框值动态生成列表。 例如,如果我的文本框值为 4,那么我可以在我的程序中定义 list1 ,list2 ,list3 ,list4 。到目前为止,我只能同时更改文本框的值和列表。 那么,我的问题是我可以根据给定的值动态生成列表吗?

这是我的代码

public List<int> L0 = new List<int>();
public List<int> L1 = new List<int>();
public List<int> L2 = new List<int>(); 

【问题讨论】:

  • 你的最终目标是什么?
  • 为什么不能使用列表?它们的大小是动态的。
  • 如果它是一个列表,为什么你不能增加它的项目?您可以创建列表列表
  • 公共列表 L0 = 新列表();公共列表 L1 = 新列表();公共列表 L2 = 新列表 ();这是我的代码。我手动定义它们,我的目标是动态定义它们。有什么好办法吗?我对C#特性不是很熟悉...

标签: c# dynamic-programming


【解决方案1】:

这是我您正在尝试做的一个示例(说实话,这个问题不是很详细。假设您的文本框包含您要创建的列表数量称为txtListCount

int count = int.Parse(txtListCount.Text); //convert text in the textbox to number
List<List<int>> myLists = new List<List<int>>(); //container for your lists
for(int i = 0; i < count; i++)
    {
        myLists.Add(new List<int>()); //create lists dynamically
    }
//myLists contains all your lists

【讨论】:

    【解决方案2】:

    您正在寻找列表。列表的大小是动态的。您可以根据需要增加大小。浏览这篇 MSDN 文章

    https://msdn.microsoft.com/en-us/library/ybcx56wz.aspx

    List<List<int>> myList = new List<List<int>>();
    
    int NoOfItems = Convert.ToInt32(txt.Text);
    
    for(int i=0;i<NoOfItems;i++)
    {
       myList.Add(new List<int>();)
    }
    

    【讨论】:

    • 好的,我明白了。列表中的列表。使用 myList[0] 引用第一个 List,对吗?这看起来很棒。非常感谢。
    猜你喜欢
    • 2012-10-28
    • 2019-12-28
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2022-08-04
    • 2016-10-29
    • 1970-01-01
    相关资源
    最近更新 更多