简体   繁体   中英

cannot convert from 'void' to 'System.Collections.Generic.List<string> C#

I'm trying to add a new List for each loop in the code below to a dictionary, but I'm currently struggling with the following error:

cannot convert from 'void' to '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
    }
}}

Since my coding skills are definitly lacking in some aspects, I figured someone with a better grasp on the language could help me out. Every help is greatly appreciated!

Welcome to SO!

List add method does not return any value: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.add?view=netframework-4.7.2 .

So, if I understood your idea correctly, you need to fill the list with needed values and add it itself to the dictionary, like this:

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 What is it Random.Range ? Is it some extention method? In any case, it seems to be dangerous to generate id's based on random value in such small interval. Why not simple use i.ToString() ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM