开发者

Casting an interface

I have the following code

  var distributionUnits = _distributionUnitRepository.FindByC开发者_运维技巧ompanyId(userSession.CompanyId);

This returns 2 records. However when i tried the following cast. I have no records.

        var myentities = distributionUnits as List<IEntity>;

Is this kind of cast possible?

Further info.

 public interface IEntity
    {
        string Name { get; set; }
    }



public class DistributionUnit : IEntity
{

   public virtual string Name { get; set; }

}


This returns 2 records. However when i tried the following cast. I have no records.

var myentities = distributionUnits as List<IEntity>;

Is this kind of cast possible?

Well, you haven't told us the return type of DistributionUnitRepository.FindByCompanyId, but probably not. You see, let's say the return type is List<DistributionUnit>. If you could make that cast, the following would be possible:

class EvilEntity : IEntity { }

myentities.Add(new EvilEntity());

and now you've just added an instance of EvilEntity to your list List<DistributionUnit> which is clearly absurd.

Further, if the return type of DistributionUnitRepository.FindByCompanyId is not even a List<DistributionUnit>, but say, IEnumerable<DistributionUnit> that is just yielded, then of course the cast is impossible.

You probably want to say

var myentitites = distributionUnits.Cast<IEntity>().ToList();


var myentities = distributionUnits.Cast<IEntity>().ToList();

assuming your distributionUnits are either IEntity or something that either inherits or implements IEntity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜