How do I convert a List to List?

后端 未结 5 1868
后悔当初
后悔当初 2020-12-30 19:04

I have an interface defined as:

public interface MyInterface {
     object foo { get; set; };
}

and a class that implements that interface:

5条回答
  •  北海茫月
    2020-12-30 19:35

    A List cannot be converted to a List in general, because the first list might contain objects that implement MyInterface but which aren't actually objects of type MyClass.

    However, since in your case you know how you constructed the list and can be sure that it contains only MyClass objects, you can do this using Linq:

    return list.ConvertAll(o => (MyClass)o);
    

提交回复
热议问题