How do I convert a List to List?

后端 未结 5 1831
后悔当初
后悔当初 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:26

    I find Automapper very useful for converting interfaces to concrete classes.

    0 讨论(0)
  • 2020-12-30 19:30

    But a List<MyInterface> is emphatically not a List<MyClass>.

    Think:

    interface IAnimal { }
    
    class Cat : IAnimal { }
    class Dog : IAnimal { }
    
    var list = new List<IAnimal> { new Cat(), new Dog() };
    

    Then

    var cats = (List<Cat>)list;
    

    Absurd!

    Also,

    var cats = list.Cast<Cat>();
    

    Absurd!

    Further

    var cats = list.ConvertAll(x => (Cat)x);
    

    Absurd!

    Instead, you could say

    var cats = list.OfType<Cat>();
    
    0 讨论(0)
  • 2020-12-30 19:35

    A List<MyInterface> cannot be converted to a List<MyClass> 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);
    
    0 讨论(0)
  • It is possible and that's where the generics shine! Here is a simple example:

    public interface ICountable
    {
         int Count { get; set; }
    }
    
    public class PopularName : ICountable
    {
        public string Name { get; set; }
        public int Count { get; set; }
    }
    
    public class PopularSize : ICountable
    {
         public int Size { get; set; }
         public int Count { get; set; }
    }
    

    And now you need to declare your method (or your class) generic like this:

    public bool HasAnyValue<T>(List<T> countableModel) where T : ICountable
    {
        return countableModel.Count > 0;
    }
    
    0 讨论(0)
  • 2020-12-30 19:42

    You could use Cast<> extension method:

    return list.Cast<MyClass>();
    
    0 讨论(0)
提交回复
热议问题