Given the following types:
public interface IMyClass { }
public class MyClass : IMyClass { }
I wonder how can I convert a List<MyClass>
to a List<IMyClass>
? I am not completely clear on the covariance/contravariance topics, but I understand that I cannot just plainly cast the List because of that.
I could come up with this trivial solution only; lacking any elegance, wasting resources:
...
public List<IMyClass> ConvertItems(List<MyClass> input)
{
var result = new List<IMyClass>(input.Count);
foreach (var item in input)
{
result.Add(item);
}
return result;
}
....
How can you solve it in a more elegant/performant way?
(Please, mind that I need .NET 2.0 solution, but for completeness, I would be happy to see the more elegant solutions using newer framework versions, too.)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…