[英](“Child Class” is “Parent class”)
我正在上HotDog班,還是Food班的孩子。
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永遠不是所提供的Food類型的,因此里面的代碼無法訪問。 知道這東西怎么了,我該如何解決?
您需要反射才能使它起作用。
首先獲取實際類型的HotDog:
Type t = Type.GetType("MyNamespace.HotDog");
現在創建這種類型的新實例:
HotDog instance = (HotDog) Activator.CreateInstance(t);
請注意,這將調用默認構造函數。 如果需要參數化,請使用Activator#CreateInstance(t, object[])
。
據我所知,問題在於您的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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.