我有两个atm相同且定义了cast的类:
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();
但这会引发无效播放异常。
有什么想法吗?
答案 0 :(得分:1)
您正在尝试将集合对象IEnumerable<SponsoredBrand>
转换为IEnumerable<SponsoredBrandViewModel>
,您已在其中为实际对象定义了隐式强制转换运算符。您需要遍历集合并创建一个新集合,例如
var dbSponsoredBrands = await this._sponsoredBrandRepository.GetAsync();
var viewModels = dbSponsoredBrands.Select(x => (SponsoredBrandViewModel)x);
答案 1 :(得分:0)
您可以使用 LINQ -Functions
.Cast<SponsoredBrandViewModel>()
或
.OfType<SponsoredBrandViewModel>()
实现这一目标。这些也将以一种懒惰的方式迭代结果。如果您确定每个元素都属于这种类型,请使用第一个元素,如果您只想过滤匹配元素,则使用后者。