简体   繁体   中英

Convert list to a class

I have classes as below

public class ClassA
{

   public int Id { get; set;}

}

public class ClassB : List<ClassA>
{

}

How do I convert List to ClassB?

I am doing simple casting as below but throws exception.

var list1=  new List<ClassA>();

var list2=  (ClassB)list1;

regards, Alan

expose a constructor to create instance of ClassB from List

public class ClassB : List<ClassA>
{
    public ClassB(IList<ClassA> source) : base(source)
    {
    }
}

then use

var list1 = new List<ClassA>();
var list2 = new ClassB(list1);

you can also expose an explicit operator to make your casting possible:

public static explicit operator ClassB(List<ClassA> source)
{
    return new ClassB(source);
}

but you can't create conversions from a base class, so you must use composition instead of inheritance, like for example:

public class ClassB : IEnumerable<ClassA>
{
    private IList<ClassA> _source;

    public ClassB(IList<ClassA> source)
    {
        _source = source;
    }

    public IEnumerator<ClassA> GetEnumerator() => _source.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => _source.GetEnumerator();

    public static explicit operator ClassB(List<ClassA> source)
    {
        return new ClassB(source);
    }
}

now it's possible to do:

var list1 = new List<ClassA>();
var list2 = (ClassB)list1;

by replacing explicit with implicit you can even skip the ClassB explicit casting but please try to not use conversion operators at all because too much magic is involved and unless you're the only developer in the project - it may confuse others

no,you can't.
parent class object cannot be converted to sub class

var list1=  new List<ClassA>();

var list2=  (ClassB)list1;

it can be simplified to below code

List<ClassA> list2 = new ClassB();

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