เมธอด Type.GetNestedType() ใน C# ใช้สำหรับดึงประเภทเฉพาะที่ซ้อนอยู่ภายใน Type ปัจจุบัน
ไวยากรณ์
เมธอดนี้มี 2 การโหลดทับ:
public Type GetNestedType (string name); public abstract Type GetNestedType (string name, System.Reflection.BindingFlags bindingAttr);
ตัวอย่าง
ตัวอย่างการใช้งานเมธอด Type.GetNestedType():
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
ตัวอย่างเพิ่มเติม
ตัวอย่างที่สองกับการส่งค่า null (จะโยนข้อยกเว้น):
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