【问题标题】:Insert variable containing string as parameter of new list c#插入包含字符串的变量作为新列表c#的参数
【发布时间】:2018-09-23 14:14:49
【问题描述】:

我有几个包含数据的列表。我的目的是通过按键显示这些列表的某些索引。所有列表的功能都相同......“按键,获取数据”。我不想为每个列表编写单独的函数。相反,我只想设置一个等于“list1”、“list2”等的变量。然后将该变量字符串插入

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 是一个字符串,它试图插入到一个期望不同类型的参数中。我不知道如何解决这个问题。我确定有人会告诉我使用反射,但我在网上查看了不同的示例,但我不知道如何将其应用于我的案例。我是 C# 的新手。有人可以帮忙吗?

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    也许List 不适合在您的情况下使用。您是否尝试过使用Dictionaries

    字典允许您根据给定的键检索对象。在您的情况下,“键”是字符串(“list1”、“list2”等),它们的关联对象(也称为“值”)是 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"];
    

    【讨论】:

    • 根据问题中的最后一行示例代码,看起来 OP 的字典将是 &lt;string, List&lt;Sprite&gt;&gt;。除此之外,这是一个很好的答案。
    • 更正了用户@clarkitect 建议的代码示例
    • 所以让我再解释一下。我的列表都包含图像,我正在创建一个随机化功能,该功能在列表中循环并随机选择一个索引然后显示它。之后我从主列表的副本中删除索引,因为我不想更改主列表。我使用列表是因为它具有 RemoveAt 功能。为了更清楚,这是我的完整代码。 List&lt;Sprite&gt; newList = new List&lt;Sprite&gt;(controlVariable); foreach(Image image in Images){ int j = Random.Range(0, newList.Count); image.sprite = newList[j]; newList.RemoveAt(j);
    • 我有 5 个列表,我想选择要分配给“controlVariable”的图像列表,以便新的“克隆”列表包含用户选择的相应主列表的图像。跨度>
    • 我相信我给出的例子符合您的需求。首先,您在字典中创建 5 个(“克隆”)列表中的每一个,例如:dict["list2"] = new List&lt;Sprite&gt;();(在字典中创建从“list1”到“list5”的每个列表)。然后,在您最后一条评论的foreach 循环之前,您将设置controlVariable 为您要使用的列表的名称(例如"list3")。最后,您可以使用 List&lt;Sprite&gt; newList = dict[controlVariable]; 并使用您刚刚发布的相同的 foreach 代码。
    猜你喜欢
    • 2011-07-19
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 2021-10-21
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    相关资源
    最近更新 更多