Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

c# - Casting an object using the "as" keyword returns null

Here are my classes definitions:

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 is of type EntityCollectionProxy<AbstractContactEntity>.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...