Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

c# - Upcasting and generic lists

I have the following class hierarchy:

public abstract class BaseData
{
  //some properties
}

public class CoData : BaseData
{
  //some properties
}

I am working with a method that requires the return type to be List<BaseData>. In the method, I have access to List<CoData>

public List<BaseData> Save()
{
  List<CoData> listCoData = GetData();
  return listCoData;
}

If I understand correctly, I can upcast from a CoData to a BaseData. But, when I have a list, it errors out even if I explicitly try to typecast.

Error:

Error   118 Cannot implicitly convert type 'System.Collections.Generic.List<CoData>' to System.Collections.Generic.List<BaseData>'

EDIT:

mquander's Conversion approach seems to work for me in 3.0

Is downcasting done the same way as well? from

ie., Can I do this - List<CoData> listCoData = listBaseData.Cast<BaseData>().ToList();

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes; welcome to variance. Ultimately, it isn't a list of BaseData - for example, if you had another subclass, a List<BaseData> would (at compile time) let you .Add it... but the runtime type wouldn't let you. The compiler is stopping you making a mistake.

In some scenarios, generics can help here... I discuss this at the end of this blog entry. Note that .NET 4.0 variance doesn't apply to lists.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...