2013-02-07 35 views
1

下面是代碼:爲什麼我越來越無法拈例外

interface IA 
{ 
} 

interface IC<T> 
{ 
} 

class A : IA 
{ 
} 

class CA : IC<A> 
{ 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     IA a; 
     a = (IA)new A(); // <~~~ No exception here 

     IC<IA> ica; 

     ica = (IC<IA>)(new CA()); // <~~~ Runtime exception: Unable to cast object of type 'MyApp.CA' to type 'MyApp.IC`1[MyApp.IA]'. 
    } 
} 

爲什麼會收到鑄造異常的代碼的最後一行?

+0

什麼版本的C#? – Rake36

+0

我認爲它是4.0 – Vlad

+1

'CA'沒有實現'IC '。 –

回答

2

需要聲明ICinterface IC<out T>爲鑄造工作。這告訴編譯器IC<A>可以分配給IC<IA>類型的變量。

請參閱,this page的解釋。

1

你可以做

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ConsoleApplication1 
{ 
    interface IPerson 
    { 
    } 

    //Have to declare T as out 
    interface ICrazy<out T> 
    { 
    } 

    class GTFan : IPerson 
    { 
    } 

    class CrazyOldDude : ICrazy<GTFan> 
    { 
    } 

    class Program 
    { 
     static void Main(string[] args) { 
      IPerson someone; 
      someone = (IPerson)new GTFan(); // <~~~ No exception here 

      ICrazy<GTFan> crazyGTFanatic; 
      ICrazy<IPerson> crazyPerson; 

      crazyGTFanatic = new CrazyOldDude() as ICrazy<GTFan>; 

      crazyGTFanatic = (ICrazy<GTFan>)(new CrazyOldDude()); 

      crazyPerson = (ICrazy<IPerson>)crazyGTFanatic; 
     } 
    } 
} 
+1

是的,但是會將'ica'設置爲空,所以它沒有幫助許多。 –

+0

@BrianRasmussen哦,你說ica永遠不會是空的?無論如何,如果你使用我的建議,你是正確的,因爲它是_is_ null。 – Rake36

+0

是的,導致演員無效,因此'as'運算符將返回null。 –