2013-01-14 37 views
0

我爲InvalidCastException問題嘗試投放的演員KeyValuePair在接口上

IList<KeyValuePair<string, object>> x 

IList<IItem> y 

其中的iItem是我的接口 我已經試過......

IList<IItem> y = (IItem) x; //INVALIDCASTEXCEPTION 

IList<IItem> y = x.Cast<IItem>().ToList(); //another exception 

...有人可以幫助我嗎?

+0

什麼是 「_another EXCEPTION_」?從來沒有聽說過。你還應該顯示你的接口和一個實現它的類。 –

+3

'IItem'是什麼類型?你能展示這個定義嗎? – codingbiz

+0

'KeyValuePair'不是'IItem',你會期望你的演員怎麼做? – svick

回答

2

一個KeyValuePar<string,object>不能被強制轉換爲你的接口定義投地IItem自己。您需要創建實現它的類的實例,然後您可以將其轉換爲接口類型。

假設這是您的接口和實現它的類:

interface IItem 
{ 
    string Prop1 { get; set; } 
    object Prop2 { get; set; } 
} 

class SomeClass : IItem 
{ 
    public string Prop1 
    { 
     get; 
     set; 
    } 

    public object Prop2 
    { 
     get; 
     set; 
    } 
} 

現在,您可以創建一個從IList<IItem>List<KeyValuePar<string,object>>

IList<KeyValuePair<string, object>> xList = ...; 
IList<IItem> y = xList 
    .Select(x => (IItem)new SomeClass { Prop1 = x.Key, Prop2 = x.Value }) 
    .ToList(); 
1

KeyValuePair<TKey, TValue>沒有實現IItem,它似乎甚至不是.NET Framework的一部分。除非已在某處重新定義KeyValuePair,否則無法投射。

編輯:即使您已定義了您的界面,也不能將IList<YourKeyValuePair>轉換爲IList<IItem>,因爲IList不是協變。但是,您可以將它投射到IEnumerable<IItem>

-1

你可以使用explicit keyword,或implicit keyword

+1

沒有IItem是一個接口 - 請參閱http://stackoverflow.com/questions/2433204/why-cant-i-use-interface-with-explicit-operator – Rhumborl

+0

「隱式」運算符純粹是編譯時構造。 'Cast'方法不會將用戶定義的隱式轉換考慮在內。 – Servy