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
412 views
in Technique[技术] by (71.8m points)

c# - .NET Casting Generic List

Can someone explain to me why in .NET 2.0 if I have an interface, IPackable and a class that implements that interface OrderItem, when I have a method that takes in a List<IPackable>, passing in a list of List<OrderItem> does not work?

Does anyone know how I could accomplish this functionality?

Code:

public interface IPackable {
        double Weight{ get; }
}

public class OrderItem : IPackable


public List<IShipMethod> GetForShipWeight(List<IPackable> packages) {
   double totalWeight = 0;
   foreach (IPackable package in packages) {
        totalWeight += package.Weight;
   }
}

The following code does not work.

List<OrderItem> orderItems = new List<OrderItem>();
List<IShipMethod> shipMethods = GetForShipWeight(orderItems);
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

JMD is half correct. In fact, it's absolutely incorrect to say that we will be able to cast a generic list with C# 4.0. It's true that covariance and contravariance will be supported in C# 4.0 but it will only works with interface and delegate and there will have a lot of constraints. Therefore, it won't work with List.

The reason is really simple.

If B is a subclass of A, we cannot say that List<B> is a subclass of List<A>.

And here's why.

List<A> exposes some covariances methods (returning a value) and some contravariances methods (accepting a value as a parameter).

e.g.

  • List<A> exposes Add(A);
  • List<B> exposes Add(B);

If List<B> inherits from List<A>...than you would be able to do List<B>.Add(A);

Therefore, you would loose all type safety of generics.


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

...