2016-09-28 81 views
0

轉換自IEnumerable 到IEnumerable的 我想要的隱式轉換添加到我的ViewModel類(VMSalesRep): 通過隱式轉換

public static implicit operator IEnumerable<VMSalesRep> (IEnumerable<QuoteSalesRep> vm) 
{ 
    IEnumerable<VMSalesRep> result = vm.Select(x => new VMSalesRep() 
    { 
     QuoteSalesRepID = x.QuoteSalesRepID, 
     FirstName = x.FirstName, 
     LastName = x.LastName, 
     CommisionPercentage = x.CommisionPercentage 
    }); 
    return result; 
} 

我需要一個IEnumerable<QuoteSalesRep>轉換爲IEnumerable<VMSalesRep>。不過,我得到的錯誤:

User-defined conversion must convert to or from the enclosing type

我做錯了什麼?

+1

請檢查這個你不能做這個http://stackoverflow.com/questions/1971925/explicit-conversion-operator-error-when-converting-generic-lists#1971935 – inan

+0

公司我工作提供的搜索引擎只爲這樣案例 - 你得到一個錯誤 - 把它放入並得到答案 - https://www.bing.com/search?q=User-defined+conversion+must+convert+to+or+from+the+enclosing+type (已授予,也有其他用途),您可以嘗試其他搜索引擎,例如https://www.google.com/?gws_rd=ssl#q=User-defined+conversion+must+convert+to+or+from +的+包圍+型 –

回答

4

您只能從類內部聲明來自或去往的隱式轉換。因此,您需要將轉換置於IEnumerable<T>的定義範圍內,因爲這是源和目標的類型,無法完成

您將無法執行從一個IEnumerable到另一個IEnumerable的隱式轉換。