问题
I have the next situation
Generic class:
public class A {
...
}
and two clases:
public class B: A {
...
}
public class C: A {
...
}
In some part of the code I want to do something like (list is filled previously):
foreach (A item in list) {
listB.add((B) item);
}
Is it possible to do it? I just want to bind the list of generic ítems to the list of clases extends the generic class.
Thanks
回答1:
You cannot do what you are trying to do because you won't be able to add items of type C
to your list of B
items
You can however
foreach(B item in list.OfType<B>())
listB.add(item);
回答2:
The solution from this is either to create a constructor for B that takes an instance of A and constructs B from it, or similarly a static method on B that you can provide an instance of A and it will return an instance of B constructed from the instance of A. Neither are ideal.
The reason why you can't do what you are attempting to is because B is a subclass of A. Therefore B will have all the required properties and methods of A and can be treated as if it were an instance of A. However A does not have all the required properties and methods of B, and therefore it cannot be treated as if it were an object of type B.
However as mentioned in one of the comments, if the item you are trying to cast as type B is actually of type B your code will work.
来源:https://stackoverflow.com/questions/17465661/clases-and-objects-in-c-sharp