我有两个类,它们是相同且已定义的类型:
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
};当它是一个数组时,我想让它强制转换。
ar dbSponsoredBrands = await this._sponsoredBrandRepository.GetAsync();
var viewModels = (IEnumerable<SponsoredBrandViewModel>) dbSponsoredBrands.ToEnumerable();但是这个抛出的无效广播异常。
有什么想法吗?
发布于 2017-06-14 17:12:39
您正在尝试将集合对象IEnumerable<SponsoredBrand>强制转换为IEnumerable<SponsoredBrandViewModel>,并在其中为实际对象定义了隐式强制转换操作符。您需要遍历集合并创建一个新的集合,例如
var dbSponsoredBrands = await this._sponsoredBrandRepository.GetAsync();
var viewModels = dbSponsoredBrands.Select(x => (SponsoredBrandViewModel)x);发布于 2017-06-14 19:15:38
您可以使用LINQ-Functions
.Cast<SponsoredBrandViewModel>()或
.OfType<SponsoredBrandViewModel>()来实现这一点。这些也会迭代结果,但以一种懒惰的方式。如果您确定每个元素都属于此类型,则使用第一个,如果只想过滤匹配的元素,则使用后一个。
https://stackoverflow.com/questions/44540202
复制相似问题