gpt4 book ai didi

c# - 隐式转换数组

转载 作者:太空宇宙 更新时间:2023-11-03 12:26:45 24 4
gpt4 key购买 nike

我有两个 atm 相同且定义了类型转换的类:

 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();

但是这会抛出 invalidcast 异常。

有什么想法吗?

最佳答案

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

var dbSponsoredBrands = await this._sponsoredBrandRepository.GetAsync();
var viewModels = dbSponsoredBrands.Select(x => (SponsoredBrandViewModel)x);

关于c# - 隐式转换数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44540202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com