2014-10-01 12 views
2
bool InContext(Class[] array, Item item) 
{ 
    for(int i = 0;i<array.length;i++) 
    { 
    if(item is array[i]) 
    { 
     return true; 
    } 
    } 
    return false; 
} 

有沒有辦法在數組中存儲一堆類,以便我可以判斷其中一個項是否從它繼承?保存類不是數組中的對象

我想要這個函數來檢查一個項目是否在上下文中(對於上下文敏感的菜單)是相當動態的。所以手動寫入不是真正的選擇。

+1

可以使用【型號】(http://msdn.microsoft.com/en-us/library/system.type(V = vs.110)的.aspx ) – Reniuz 2014-10-01 08:06:10

回答

10

使用Type而不是您的標題行中的'Class'。

然後,你可以有:

bool InContext(Item item, Type[] accepted) 
{ 
    Type itemType = item.GetType(); 

    return accepted.Any(x=> x.IsAssignableFrom(itemType)); 
} 
相關問題