Say I have a method that is expecting a generic collection parameter of a base type, see Test.MethodA(IEnumerable(BaseClass) listA) below. How come when I pass it a collection of a derived type the code wont build? Wouldn't all instances of DerivedClass also be a BaseClass?
I could have just created a new List(BaseClass) and passed that to MethodA(IEnumerable(BaseClass) listA). But I would think C# would be smart enough to know that a collection of DerivedClass has all the same properties as a collection of BaseClass.
Is using the List.Cast(T)() method as I've shown the best way to solve this problem?
abstract class BaseClass
{
public int SomeField;
public abstract string SomeAbstractField
{
get;
}
}
class DerivedClass:BaseClass
{
public override string SomeAbstractField
{
get { return "foo"; }
}
}
class TestClass
{
public void MethodA(IEnumerable<BaseClass> listA)
{
}
public void MethodB()
{
List<DerivedClass> listB = new List<DerivedClass>();
//Error 16 The best overloaded method match for
//TestClass.MethodA(List<BaseClass>)'
//has some invalid arguments
this.MethodA(listB);
//this works
this.MethodA(listB.Cast<BaseClass>());
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…