I will start with code
class LocData
{
public virtual TypeA Copy () { ... }
...
}
class LocDataCollection<T> : List<T> where T: LocData
{
public LocDataCollection<T> Copy()
{
LocDataCollection<T> locDatas = new LocDataCollection<T>();
foreach (T locData in this)
{
T locData2 = locData.Copy() as T;
locDatas.Add(locData2);
}
return locDatas;
}
...
}
and
class TypeA : LocData
{
public new TypeA Copy () { ... }
...
}
class TypeACollection : LocDataCollection<TypeA>
{
}
test code:
TypeACollection typeAs = new TypeACollection();
...
TypeACollection typeAs2 = typeAs.Copy();
compile message:
“Cannot implicitly convert type ‘LocDataCollection’ to ‘TypeACollection’. An explicit conversion exists (are you missing a cast?)”
I have to change to
TypeACollection typeAs2 = typeAs.Copy() as TypeACollection;
compile pass but at run time error out. typeAs2 return as null even typeAs is not null.
typeAs.Copy()returns aLocDataCollection<TypeA>. But you cannot assign one of those to aTypeACollectionbecauseTypeACollectionis more derived thanLocDataCollection<TypeA>.You could perhaps solve the problem by making your copy method receive a
LocDataCollection<T>:and then at the call site:
Of course, this won’t copy any of the
TypeACollectionspecific stuff, unless you added an override to that effect.But I don’t really know enough about your problem to be confident that this is an appropriate solution.