नाम से विशिष्ट नेस्टेड टाइप प्राप्त करने के लिए Type.GetNestedType() मेथड का उपयोग करें।
सिंटैक्स
public Type GetNestedType(string name);
public Type GetNestedType(string name, BindingFlags bindingAttr);
उदाहरण 1: मौजूदा नेस्टेड टाइप प्राप्त करना
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
उदाहरण 2: नल नाम पास करना (एक्सेप्शन)
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
महत्वपूर्ण बिंदु
nameपैरामीटर नल नहीं हो सकता -ArgumentNullExceptionफेंकता है- केस-सेंसिटिव नाम मिलान
- यदि नहीं मिला तो
nullलौटाता है (एक्सेप्शन नहीं) BindingFlagsओवरलोड नॉन-पब्लिक नेस्टेड टाइप्स के लिए अनुमति देता है
BindingFlags के साथ नॉन-पब्लिक नेस्टेड टाइप
using System;
using System.Reflection;
public class Subject {
public class PublicNested { }
private class PrivateNested { }
protected class ProtectedNested { }
}
public class Demo {
public static void Main() {
Type type = typeof(Subject);
// पब्लिक (डिफ़ॉल्ट)
var publicNested = type.GetNestedType("PublicNested");
Console.WriteLine("Public: " + publicNested);
// नॉन-पब्लिक
var privateNested = type.GetNestedType("PrivateNested", BindingFlags.NonPublic);
Console.WriteLine("Private: " + privateNested);
var protectedNested = type.GetNestedType("ProtectedNested", BindingFlags.NonPublic);
Console.WriteLine("Protected: " + protectedNested);
// मौजूद नहीं
var missing = type.GetNestedType("Missing");
Console.WriteLine("Missing: " + missing); // null
}
}
आउटपुट
Public: Subject+PublicNested
Private: Subject+PrivateNested
Protected: Subject+ProtectedNested
Missing:
GetNestedType vs GetNestedTypes
| मेथड | रिटर्न | उपयोग |
|---|---|---|
GetNestedType(name) | Type (सिंगल) | नाम से विशिष्ट नेस्टेड टाइप |
GetNestedTypes() | Type[] (ऐरे) | सभी नेस्टेड टाइप्स |