c# - Passing a generic collection of objects to a method that requires a collection of the base type -


I have a method that is expecting the base type of general archive parameter, Test.MethodA ( IEnumerable list A) How can this happen when I make it a collection of derivative type which does not create a code? All examples of DerivedClass can also be made of a BaseClass

I can create a new list (base class) And passed the method A (IEnumerable listA) but I would think it would be sensible enough that DerivedClass has all the same properties as a collection of BaseClass in the collection.

List. Using the Cast (T) () method as I have been shown, the best way to solve this problem has been shown?

  Abstract class base class {public integer some fields; Public abstract string SomeAbstractField {get; }} Category DerivedClass: Base Class {Public Override String SomeAbstractField {get {return "foo"; }}} Class test class {public zero method (ienumerable & lt; base class & gt; list a) {} public zero methode () {list & lt; DerivedClass & gt; ListB = new list & lt; DerivedClass & gt; (); // The best overloaded method for error // //TestClass.MethodA(List<BaseClass>) '// Matching has some invalid argument in this. Method A (listB); // Does it work. MethodA (listB.Cast & lt; BaseClass & gt; ()); }}  

cast & lt; & Gt; () The best way to solve it at this time will be to work fine in your original version C # 4.0 / .NET 4.0, however, where IEnumerable & lt; T & gt; Code is T .

(I have just verified that it is compiled under .NET 4.0 Beta 1.)

As long as the .NET 4.0 and C # 4 exits, generics are irreversible Are - IEnumerable & lt; Object & gt; and IEnumerable & lt; String & gt; are effectively unrelated interfaces, even in .NET 4.0, you can list & lt; T & gt; will not be able to do this as the parameter type - only the interface and the representative will be different, and even when the type parameter <<>

to learn more about the variance in C # 4 Read the excellent about Eric Liperte.


Comments

Popular posts from this blog

c# - ListView onScroll event -

PHP - get image from byte array -

Linux Terminal Problem with Non-Canonical Terminal I/O app -