Why does this generic cast fail?

前端 未结 4 963
慢半拍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: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. (Unless I'm missing something), for a general purpose solution you'll need two due to generic constraint limitations:

    public class UpCastList : IList
        where FromType : ToType
    
    public class DownCastList
        where ToType : FromType
    

    The other possibility is delegating the conversion:

    public class CastList : IList
    {
        public CastList(IList source, Func converter) { ... }
    }
    

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

提交回复
热议问题