在 C# 中獲取當前型別內巢狀的特定型別


要獲取當前型別中巢狀的特定型別,程式碼如下所示 -

示例

 即時演示

using System;
public class Demo {
   public static void Main() {
      Type type1 = typeof(Subject);
      try {
         Type type2 = type1.GetNestedType("AdvSubject");
         Console.Write("NestedType = "+ type2);
      }
      catch (ArgumentNullException e) {
         Console.Write("{0}", e.GetType(), e.Message);
      }
   }
}
public class Subject {
   public class BasicSubject {
      //
   }
   public class AdvSubject {
      //
   }
}

輸出

這將產生以下輸出 -

NestedType = Subject+AdvSubject

示例

我們來看另一個示例 -

 即時演示

using System;
public class Demo {
   public static void Main() {
      Type type1 = typeof(Subject);
      try {
         Type type2 = type1.GetNestedType(null);
         Console.Write("NestedType = "+ type2);
      }
      catch (ArgumentNullException e) {
         Console.Write("{0}", e.GetType(), e.Message);
      }
   }
}
public class Subject {
   public class BasicSubject {
      //
   }
   public class AdvSubject {
      //
   }
}

輸出

這將產生以下輸出 -

System.ArgumentNullException

更新於:11-12-2019

58 個瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告