简体   繁体   中英

Convert list<base> class to list<derived> class in silverlight

I have a base class(Directory) that has following parameters :

string Name;
string Path;
List<Directory> SubDirectory;

Now i want to make a new class that will be extension of this class with a new property :

Bool Valid ;

so i write the following code for the derived class (DirectoryExt):

Public class DirectoryExt : Directory

{
    Public bool Valid {get; set;}

    public DirectoryExt( Directory directory)

    {
       this.Name = directory.Name;
       this.Path = directory.Path;
       this.SubDirectory = directory.Subdirectory;
       this.Valid = false;
    } 

}

The problem here is how to convert this List<Directory> SubDirectory into List<DirectoryExt> SubDirectory when i create a DirectoryExt(derived) object from an existing Directory(bas e) object ??

Can anyone suggest a solution?

使用LINQ来对象:

this.SubDirectory = directory.SubDirectory.Select(s => new DirectoryExt(s)).ToList();

this.SubDirectory = new ObservableCollection< Directory >();

        if (directory.SubDirectory != null || directory.SubDirectory.Count != 0)
        {
            foreach (var item in directory.SubDirectory.Select(s => new DirectoryExt(s)).ToList())
            {
                this.SubDirectory.Add(item);
            }
        }

This is correct solution to it... i have tested it and it worked.

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