使用“ as”投射对象关键字返回null [英] Casting an object using the "as" keyword returns null

查看:66
本文介绍了使用“ as”投射对象关键字返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的类定义:

public abstract class AbstractEntity : ...
public partial class AbstractContactEntity : AbstractEntity, ...
public sealed class EntityCollectionProxy<T> : IList<T>, System.Collections.IList 
where T : AbstractEntity

现在从委托那里得到一个对象,我想将其强制转换,但是它并没有按我期望的那样工作。

Now I get an object from a delegate and I want to cast it, and it doesn't work as I expect it to.

var obj = resolver.DynamicInvoke (this.entity);
var col = obj as EntityCollectionProxy<AbstractEntity>;

obj 类型为 EntityCollectionProxy< AbstractContactEntity>

但是 col 为空。
如果我尝试常规转换(var col = (Entity ...)obj ),我会得到一个例外。

But col is null. If I try the regular casting (var col = (Entity...) obj) I get an exception.

我希望它能工作,因为类型是连贯的。
我想念什么?

I would expect that it work since the types are coherent. What do I miss?

推荐答案

它们不是同一类型。它与 List< string> List< int> 相同:它们也不能强制转换为另一个。 AbstractContactEntity AbstractEntity 并不会改变它。
EntityCollectionProxy< T> 提取接口并将其设为协变量也不起作用,因为您要实现 IList< T> 表示您具有输入参数,并且返回的类型为 T 的值可防止协方差。

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.

可能的解决方案如下:

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

col 的类型为 IEnumerable< AbstractEntity> 。如果您想拥有一个 EntityCollectionProxy< AbstractEntity> ,则需要创建一个新的:

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);

这假设您的 EntityCollectionProxy< T> 类具有一个接受 IEnumerable< T> 的构造函数。

但是请注意,这将是一个NEW实例,与<$返回的不一样c $ c> resolver.DynamikInvoke 。

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.

这篇关于使用“ as”投射对象关键字返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆