2014-10-08 195 views
0

我有一個HotDog類作爲Food類的一個子類。(「Child Class」是「Parent class」)

public class HotDog : Food 
{ 
    public HotDog() : base ("hotdog", new string[] { "bread", "meat"}, new int[] { 1, 1 }, 0.7) 
    { 
    } 
} 

我試圖做到這一點

Type t = typeof("HotDog"); 
if (t is Food) { 
    Food f = (Food)Food.CreateOne (t); 
} 

這是我CreateOne方法

public static Consumables CreateOne (Type t) 
{ 
    return (Consumables)Activator.CreateInstance (t); 
} 

但我得到的t是所提供的食品種類的從來都不是錯誤,以便裏面的代碼是不可達。任何想法這個東西有什麼問題,我該如何解決它?

+1

'Hot Dog'!='HotDog'。 – 2014-10-08 06:31:48

回答

0

據我所見,問題在於你的if語句。

Type t = typeof(...); 
if (t is Food) { ... } 

is的操作者檢查左側表達式的類型是否是正確的表達的一個有效值。

換句話說,您正在檢查t(它是Type)的類型是否爲Food類的有效值,當然這不是。

你可以做的是使用Type.IsAssignableFrom

if (typeof(Food).IsAssignableFrom(t)) { ... } 

IsAssignableFrom決定爲t的實例是否可以被分配到typeof(Food)類型,即一個變量,如果你能做到返回true

Hotdog h; 
Food f; 

if (typeof(Food).IsAssignableFrom(typeof(Hotdog)) 
{ 
    f = h; // you can assign a Hotdog to a Food 
} 

// this would return false for your classes 
if (typeof(Hotdog).IsAssignableFrom(typeof(Food)) 
{ 
    h = f; // you can assign a Food to a Hotdog 
} 
+0

這是正確的@@。仍然沒有得到IsAssignableFrom。你可以點亮我嗎? – 2014-10-08 07:08:46

+0

@TreeNguyen我已經添加了一個解釋,我希望這有助於。 – Dirk 2014-10-08 07:17:24

+0

這很清楚:)。 Tq這麼多:) – 2014-10-08 07:24:25

1

你需要思考得到這個工作。

首先獲得實際類型熱狗:

Type t = Type.GetType("MyNamespace.HotDog"); 

現在創建這種類型的新實例:

HotDog instance = (HotDog) Activator.CreateInstance(t); 

注意,這將調用默認的構造函數。如果您需要參數化,則使用Activator#CreateInstance(t, object[])代替。

+0

爲什麼在直接訪問,創建和調用類型時使用反射 – 2014-10-08 06:41:54

+0

嗯,它也可以在沒有Type.GetType的情況下正常工作,但無論如何它的反射在使用激活器時......但是我專注於OPs文章本身他使用字符串來獲取實際的類型。 – HimBromBeere 2014-10-08 06:47:14

+0

問題是因爲HotDog是一種食物,所以我想嘗試如果(t是食物)。但它永遠不會回報真實! – 2014-10-08 06:49:02

0

以下可能是一種更簡單的方法來檢查內部類型是否爲Food類型(使用as運算符),它檢查是否可以將一種類型轉換成基類型

Type t = typeof("Hot Dog"); 

Food isFood = t as Food; 

if(isFood != null) 
{ 
    Food f = (Food)Food.CreateOne (t); 
}