Casting an object using the “as” keyword returns null

后端 未结 1 1911
梦毁少年i
梦毁少年i 2020-12-10 21:41

Here are my classes definitions:

public abstract class AbstractEntity : ...
public partial class AbstractContactEntity : AbstractEntity, ...
public sealed cl         


        
相关标签:
1条回答
  • 2020-12-10 22:02

    They are not the same types. It is the same as with List<string> and List<int>: They also can't be casted to one another. That AbstractContactEntity is a AbstractEntity doesn't change this. Extracting an interface from EntityCollectionProxy<T> and making it covariant doesn't work either, because you want to implement IList<T> which means you have input paramaters and return values of type T which prevents covariance.

    The only possible solution is the following:

    var tmp = (EntityCollectionProxy<AbstractContactEntity>)obj;
    var col = tmp.Select(x => (AbstractEntity)x);
    

    col will be of type IEnumerable<AbstractEntity>. If you want to have a EntityCollectionProxy<AbstractEntity>, you need to create a new one:

    var result = new EntityCollectionProxy<AbstractEntity>(col);
    

    This assumes that your EntityCollectionProxy<T> class has a constructor that accepts an IEnumerable<T>.
    But beware, this will be a NEW instance and not the same as returned by resolver.DynamikInvoke.

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