2012-05-09 21 views
1

我該怎麼做類似以下的事情?
我的A對象在調用GetB後爲空,即使A繼承自B函數多態性。 A:B時返回B爲A爲空

class Program 
{ 
    public class A : B 
    { 
    } 

    public class B 
    { 
    } 

    static void Main(string[] args) 
    { 
     A a = GetB() as A; 
     Console.WriteLine(a == null); // it is null! 

     Console.WriteLine("Console.ReadKey();"); 
     Console.ReadKey(); 
    } 
    public static B GetB() 
    { 
     return new B(); 
    } 
} 
+1

C類:B {}。 C和A?很明顯不是。怎麼會這樣?那麼,爲什麼你認爲你應該能夠將任何* B投給A? A繼承B,而不是相反。 A是B,很清楚。 B'它可能是CD或者它可能只是普通的老B。 –

+0

@AnonyPegram在下面看到我的回答,我們覺得太像了...... – goric

+0

錯誤是[更明顯](http://c2.com/cgi/wiki?FailFast)如果你做老式的鑄造。即'A a =(A)GetB()' –

回答

1

你試圖將你的B下注到一個A.你不能這樣做,也不是有意義的,因爲我們不知道B是否會成爲A.最好是構建一個構造函數在A類中,它將B作爲參數。

public class A : B 
{ 
    public A(B b) 
    { 
     //perform your conversion of a B into an A 
    } 
} 

public class B 
{ 
    public B(){} 
} 

static void Main(string[] args) 
{ 
    B b = new B(); 
    A a = new A(b); 
    Console.WriteLine(a == null); // it is null! 

    Console.WriteLine("Console.ReadKey();"); 
    Console.ReadKey(); 
} 
4

您在函數中可能意思是return new A();。目前,您正試圖將B降至A,這不起作用。

1

答對了逆轉:

class Program 
{ 
    public class A : B // should be: public class A 
    { 
    } 

    public class B // should be: public class B : A 
    { 
    } 

    static void Main(string[] args) 
    { 
     // If you reverse the inheritance on code above 
     // As Ben Voigt noticed, *as A* is redundant. should be removed 
     // A a = GetB() as A; 

     // should be this. B is wider than A, so A can accept B, no need to cast 
     A a = GetB(); 
     Console.WriteLine(a == null); // it is null! 

     Console.WriteLine("Console.ReadKey();"); 
     Console.ReadKey(); 
    } 
    public static B GetB() 
    { 
     return new B(); 
    } 
} 
+1

在這種情況下,你根本不需要'as'。 –

+0

我複製粘貼他的代碼,並突出顯示錯誤的主要原因 –

1

您將無法執行此類型轉換,因爲B很好可能不是A!當然,AB的一個子類,因此您可以始終執行GetA() as B;。但換個方式是沒有道理的;很可能A的一個實例通過B的實例提供了一些附加功能。

考慮添加第三個類,C : B。如果你的功能GetB()實際上返回了new C()?這很好,因爲CB。但是當然你不希望能夠把這個投射到AAC幾乎肯定沒什麼共同之處。

相關問題