Why does this generic cast fail?

前端 未结 4 945
慢半拍i
慢半拍i 2020-12-18 10:16

I have the following inheritance:

internal abstract class TeraRow{}

internal class xRow : TeraRow {} // xRow is a child of TeraRow

public IEnumerable

        
相关标签:
4条回答
  • 2020-12-18 10:26

    You need to cast it because IEnumerable<T> is not covariant on T. You can do this:

    return result.Cast<TeraRow>();
    
    0 讨论(0)
  • 2020-12-18 10:35

    If you need the casted list to perform like the original reference (setting an item at an index also sets the item in the original collection, you can create a wrapper class that implements IList<T>. (Unless I'm missing something), for a general purpose solution you'll need two due to generic constraint limitations:

    public class UpCastList<FromType, ToType> : IList<ToType>
        where FromType : ToType
    
    public class DownCastList<FromType, ToType : IList<ToType>
        where ToType : FromType
    

    The other possibility is delegating the conversion:

    public class CastList<FromType, ToType> : IList<ToType>
    {
        public CastList(IList<FromType> source, Func<FromType, ToType> converter) { ... }
    }
    

    Edit: if you only need an IEnumerable<T>, then you can use the Cast<T> extension method as mentioned earlier.

    0 讨论(0)
  • 2020-12-18 10:37

    You're running afoul of contravariance. You'd need c# 4.0 for that to work. The type IEnumerable can't be exchanged for IEnumerable in 2.0 to 3.5. The msdn article on it is http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx

    0 讨论(0)
  • 2020-12-18 10:51

    See this question: .NET Casting Generic List

    0 讨论(0)
提交回复
热议问题