首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >隐式转换数组

隐式转换数组
EN

Stack Overflow用户
提问于 2017-06-14 17:02:48
回答 2查看 226关注 0票数 2

我有两个类,它们是相同且已定义的类型:

代码语言:javascript
复制
 public static implicit operator SponsoredBrandViewModel(SponsoredBrand sponsoredBrand)
        =>
            new SponsoredBrandViewModel
            {
                Id = sponsoredBrand.Id,
                BrandId = sponsoredBrand.RelatedEntityId,
                To = sponsoredBrand.To,
                From = sponsoredBrand.From,
                Importance = sponsoredBrand.Importance
            };
    public static implicit operator SponsoredBrand(SponsoredBrandViewModel sponsoredBrandViewModel)
        =>
            new SponsoredBrand
            {
                Id = sponsoredBrandViewModel.Id,
                RelatedEntityId = sponsoredBrandViewModel.BrandId,
                To = sponsoredBrandViewModel.To,
                From = sponsoredBrandViewModel.From,
                Importance = sponsoredBrandViewModel.Importance
            };

当它是一个数组时,我想让它强制转换。

代码语言:javascript
复制
ar dbSponsoredBrands = await this._sponsoredBrandRepository.GetAsync();
            var viewModels = (IEnumerable<SponsoredBrandViewModel>) dbSponsoredBrands.ToEnumerable();

但是这个抛出的无效广播异常。

有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2017-06-14 17:12:39

您正在尝试将集合对象IEnumerable<SponsoredBrand>强制转换为IEnumerable<SponsoredBrandViewModel>,并在其中为实际对象定义了隐式强制转换操作符。您需要遍历集合并创建一个新的集合,例如

代码语言:javascript
复制
var dbSponsoredBrands = await this._sponsoredBrandRepository.GetAsync();
var viewModels = dbSponsoredBrands.Select(x => (SponsoredBrandViewModel)x);
票数 2
EN

Stack Overflow用户

发布于 2017-06-14 19:15:38

您可以使用LINQ-Functions

代码语言:javascript
复制
.Cast<SponsoredBrandViewModel>()

代码语言:javascript
复制
.OfType<SponsoredBrandViewModel>()

来实现这一点。这些也会迭代结果,但以一种懒惰的方式。如果您确定每个元素都属于此类型,则使用第一个,如果只想过滤匹配的元素,则使用后一个。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44540202

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档