开发者

Casting an interface

开发者 https://www.devze.com 2023-02-09 23:19 出处:网络
I have the following code var distributionUnits = _distributionUnitRepository.FindByC开发者_运维技巧ompanyId(userSession.CompanyId);

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

精彩评论

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