代码之家  ›  专栏  ›  技术社区  ›  maximus1127

插入包含字符串的变量作为新列表c的参数#

  •  1
  • maximus1127  · 技术社区  · 7 年前

    List<Sprite> newList = new List<Sprite>(controlVariable);
    

    所以本质上我要找的是这个模式:

    //...user input to set value of controlVariable (this functionality is not part of this question, i'm only interested in the variable stuff below)
    string controlVariable = "list1";
    List<Sprite> newList = new List<Sprite>(controlVariable);
    

    这将允许我将我的所有代码应用到我试图使用的列表中,而不必为每种类型的列表编写新代码。但我遇到的麻烦是 controlVariable 是一个字符串,它试图插入到一个需要不同类型的参数中。我不知道该怎么解决这个问题。我肯定有人会告诉我使用反射,但我在网上看了不同的例子,我不知道如何把它应用到我的案件。我是新来的。有人能帮忙吗?

    1 回复  |  直到 7 年前
        1
  •  4
  •   vinicius.ras    7 年前

    List 不适合你的案子。你用过吗 Dictionaries ?

    字典允许您根据给定的键检索对象。在您的例子中,“keys”是字符串(“list1”、“list2”等),它们的相关对象(也称为“values”)是 Sprite

    // Creating a dictionary and adding a key to it
    Dictionary<string, List<Sprite>> dict = new Dictionary<string, List<Sprite>>();
    dict["list1"] = new List<Sprite>();
    dict["list2"] = new List<Sprite>();
    
    // Retrieving a list of sprites associated to "list1" from the dictionary
    List<Sprite> mySprList = dict["list1"];