簡體   English   中英

將System.Type強制轉換為特定的類

[英]Casting System.Type to a specific class

我正在使用反射獲取所需的System.Type。 我需要檢查它是否是Component類的后代。 如果是這樣,我需要將此特定的類添加到列表。 轉換類型的正確方法是什么?

  foreach (Type curType in allTypes)
  {
     if (curType descends from Component)
       componentsList.Add( (Component)curType );
  }

您可以使用IsSubClassOf

if (typeof(Component).Equals(curType) || curType.IsSubClassOf(typeof(Component)))
{ }

盡管如此, Type仍然是type ,而不是instance ,因此,如果您考慮將實例添加到列表中,則應檢查實例,而不是類型。

如果你有一個實例,你最好使用is

if (instance is Component)
{ }

如果打算創建特定類型的新實例,請使用Activator.CreateInstance

object instance = Activator.CreateInstance(curType);

您正在尋找IsSubClassOf方法。 注意:如果curTypeComponent類型相同,則將報告false。 在這種情況下,您可能需要添加Equals檢查。

if (curType.IsSubclassOf(typeof(Component)))
{
    //Do stuff
}

類型的轉換是不可能的,但是正如您在注釋中所說:

我需要創建所有類型的列表

因此,使您的componentlist類型為List<Type> ,然后將類型添加到該列表中。

您已經檢查了它們是否已經從Component繼承,因此只有那些類型將最終出現在該列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM