2013-09-25 136 views
0

我想看看是否有可能在一個comparison.I有下面的代碼使用System.Type的一個變量:檢查類是否是使用變量的類型?

internal ObservableCollection<FREQUENCY> GetFrequencies(System.Type equipmenttype) 
    { 
     ... 
     foreach (var incident in query) 
     { 

      if (typeof(equipmenttype).IsSubclassOf(typeof(incident))) 
      { 
       foreach (var freq in incident.FREQUENCY) 
       { 
        freqs.Add(freq); 
       } 
      } 
     } 
     return freqs; 
    } 

但變量「TMP」和「equipmenttype」拉錯誤「類型或命名空間名稱‘TMP’找不到(是否缺少using指令或程序集引用?)」

我明白,這通常是用來說的typeof(MYCLASS),但我很好奇,如果這可以使用System.Type的變量,或者如果有任何方法可以這樣做。謝謝。

+0

我不相信'typeof(incident)'會編譯,因爲它是一個引用,而不是一個類型。它應該是'incident.GetType()'。 – BACON

+0

查看Reflection API:http://msdn.microsoft.com/en-us/library/ms173183%28v=vs.90%29.aspx – JNYRanger

回答

4

我看不到您的代碼在tmp的位置。但肯定你錯過了這個

if (typeof(equipmenttype).IsSubclassOf(typeof(incident))) 

應該

if (equipmenttype.IsSubclassOf(incident.GetType())) 

typeof運營商來獲得一個類型的RuntimeType。但是你已經有了RuntimeType這是equipmenttype,所以你不需要在這裏使用typeof

+0

這很有道理。非常感謝!我從來沒有嘗試過這樣的事情。 –

+0

@JohnEdwards不客氣.. –

2

嘗試if (equipmenttype.IsSubclassOf(incident.GetType())equipmenttype已經是System.Type,必須調用GetType()來確定實例的類型。

相關問題