2017-06-14 80 views
2

我有兩個類大氣壓相同,並定義投:隱式轉換陣列

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異常。

任何想法?

回答

1

您正在嘗試將集合對象IEnumerable<SponsoredBrand>轉換爲IEnumerable<SponsoredBrandViewModel>,其中您已爲實際對象定義了隱式轉換運算符。您需要遍歷集合並創建一個新集合,例如

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

是的,沒有迭代的選擇。 – Nerf

+0

正確,每個物體必須單獨鑄造。如果迭代呈現性能問題,則可以採用懶惰方法來投射,並將其推遲到每個視圖模型被使用而不是一次全部使用。請查看[Enumerable.Cast ](https://msdn.microsoft.com/en-us/library/bb341406(v = vs.110).aspx)瞭解更多信息。 –

0

可以使用LINQ -functions

.Cast<SponsoredBrandViewModel>() 

.OfType<SponsoredBrandViewModel>() 

來實現這一目標。這些將迭代結果,但以一種懶惰的方式。如果您確定每個元素都屬於此類型,請使用第一個元素,如果您只想過濾匹配元素,請使用第一個元素。