简体   繁体   中英

C# Add two different objects into list

Hi I want to add two different objects into a list object.

The code is as follows:

try
{
    List<SerializeCls> serclsres = new List<SerializeCls>();

    serclsres = pr2.FirstMethod();

    serclsres = pr1.GenerateFile();                        
    XmlSerializer xs = new XmlSerializer(typeof(List<SerializeCls>)); //SerializeCls//,extratypes//SerializeCls
    using (FileStream fs = new FileStream(string path, FileMode.Create))
    {                                
        xs.Serialize(fs,serclsres);
        fs.Close();
    }
    Console.WriteLine("Succesfully serialized to XML");
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}

From the above code I want to add pr2.FirstMethod & pr1.GenerateFile into list object serclsres Please help me to solve this. I am new to C#.

List<List<SerializeCls>> serclsres = new List<List<SerializeCls>>();
serclsres.Add(pr2.FirstMethod());
serclsres.Add(pr1.GenerateFile());

If you want some serclsres to have type List<SerializeCls> , you have to use AddRange like this:

List<SerializeCls> serclsres = new List<SerializeCls>();
serclsres.AddRange(pr2.FirstMethod());
serclsres.AddRange(pr1.GenerateFile());

If you have this error "cannot convert from 'System.Collections.Generic.List<ConsoleTask5SerialwithAdd.SerializeCls>' to 'ConsoleTask5SerialwithAdd.SerializeCls' "

Try this

List<List<SerializeCls>> serclsres = new List<List<SerializeCls>()>;
serclsres.Add(pr2.FirstMethod());
serclsres.Add(pr1.GenerateFile());

So you will have a collection of lists, a "List of Lists".

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