c# - 无法从 'void' 转换为 'System.Collections.Generic.ListC#
问题描述
我正在尝试将下面代码中的每个循环的新列表添加到字典中,但我目前正在努力解决以下错误:
无法从 'void' 转换为 'System.Collections.Generic.List
public class WeaponGen{
Dictionary<string, List<string>> weapons = new Dictionary <string, List<string>>();
public void WeaponGeneration(int GenerationCount)
{
Weapon weapon = new Weapon(); //this class contains basic calculation methods
weapons.Clear();
for (int i = 0; i < GenerationCount; i++)
{
string listname = "weapon" + i;
string id = Random.Range(1, 41).ToString();
List<string>[] _lists = new List<string>[GenerationCount];
_lists[i] = new List<string>();
weapons.Add(listname, _lists[i].Add(id)); //this line throws an error
weapons.Add(listname, _lists[i].Add(weapon.GetName(id))); //this line throws an error
weapons.Add(listname, _lists[i].Add(weapon.GetRarity(id))); //this line throws an error
weapons.Add(listname, _lists[i].Add(weapon.GetType(id))); //this line throws an error
weapons.Add(listname, _lists[i].Add(weapon.GetDmg(id).ToString())); //this line throws an error
weapons.Add(listname, _lists[i].Add(weapon.GetSpeed(id).ToString())); //this line throws an error
weapons.Add(listname, _lists[i].Add(weapon.GetCost(id).ToString())); //this line throws an error
}
}}
由于我的编码技能在某些方面确实缺乏,我认为对语言有更好掌握的人可以帮助我。非常感谢您的每一次帮助!
解决方案
欢迎来到 SO!
列表add
方法不返回任何值:https ://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.add?view=netframework-4.7.2 。
因此,如果我正确理解了您的想法,您需要用所需的值填充列表并将其本身添加到字典中,如下所示:
for (int i = 0; i < GenerationCount; i++)
{
string listname = "weapon" + i;
string id = Random.Range(1, 41).ToString();
List<string>[] _lists = new List<string>[GenerationCount];
_lists[i] = new List<string>();
_lists[i].Add(id);
_lists[i].Add(weapon.GetName(id));
_lists[i].Add(weapon.GetRarity(id));
_lists[i].Add(weapon.GetType(id));
_lists[i].Add(weapon.GetDmg(id).ToString());
_lists[i].Add(weapon.GetSpeed(id).ToString());
_lists[i].Add(weapon.GetCost(id).ToString());
weapons.Add(listname, _lists[i]);
}
PS这是什么Random.Range
?是某种扩展方法吗?无论如何,在如此小的间隔内基于随机值生成 id 似乎是危险的。为什么不简单使用i.ToString()
?
推荐阅读
- r - 使用 R 进行精算练习
- c++ - 删除创建的类对象的属性
- android - 按钮单击不同的活动,具体取决于案例
- javascript - 组件未在反应中定义?
- python-3.x - Pandas:在执行 sum()、mean() 操作时忽略特定(坏)单元格
- node.js - Azure DevOps Pipelines - 运行 bash 脚本时出现“nodejs:找不到命令”
- javascript - Mmenu - 如何检测关闭的回调事件?
- postgresql-12 - 如何在postgres 12中查看最近是否已读取表
- shell - 符号链接会对原始文件产生负面影响吗?
- javascript - 如何对 luxon 对象数组执行排序